简体   繁体   English

如何将数组中的 char 转换为 int (JavaScript)

[英]How to convert char to int in array (JavaScript)

How to change char value in array to int value?如何将数组中的char值更改为int值? and detect first element and second element in array并检测数组中的第一个元素和第二个元素

arr = [a,a,a,b,b,a,b]

first element = a第一个元素 = a

second element = b第二个元素 = b

a = 1, b = 2

My expected output我的预期 output

arr = [1,1,1,2,2,1,2]

Something like this should work (I used NodeJs console):像这样的东西应该可以工作(我使用了 NodeJs 控制台):

> let a = ['a','a','a','b','b','a','b']
undefined
> a
[
  'a', 'a', 'a',
  'b', 'b', 'a',
  'b'
]
> var result = []
> for (var i = 0; i < a.length; i++){
... result.push(a[i].charCodeAt(0))
... }
7
> result
[
  97, 97, 97, 98,
  98, 97, 98
]

You can do it like so.你可以这样做。

You can only get the char code of an index in a string.您只能获取字符串中索引的字符代码。 Since we have an char array we can alsways get the index of 0 .由于我们有一个 char 数组,我们总是可以得到0的索引。 The smallest charcode is of A which is 65. In this example I transform a to A which resolves to 65 then I remove 64 since a should be 1 .最小的字符代码是A ,它是 65。在这个例子中,我将a转换为A ,它解析为65然后我删除 64 因为a应该是1 Consecutively b is mapped to B which is 65 and resolves to 2 since 64 is removed连续b映射到B是 65 并解析为2因为 64 被删除

 const arr = ['a','a','a','b','b','a','b'] const res = arr.map(char => char.toUpperCase().charCodeAt(0) - 64) console.log(res)

do this arr.map((x)=>{ return x.toString()})这样做 arr.map((x)=>{ return x.toString()})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM