简体   繁体   English

有人可以解释一下这段代码的第二部分吗?

[英]Can someone explain me the second part of this code please?

let a = [101, 103, 222, 97, 105];

var i = 0;
a.forEach(function(v){
  v == 97 || v == 101 || v == 105 || v==111 || v ==117 ? a[i++] = String .fromCharCode(v) : a[i++] = v;}),a;


console.log(a);

result: [ 'e', 103, 222, 'a', 'i' ]结果:['e', 103, 222, 'a', 'i']

I do understand we are looping through the array and looking for any matching values and i know what the rest of the code does, but I don't understand the part after the ?我明白我们正在遍历数组并寻找任何匹配的值,我知道代码的 rest 是做什么的,但我不明白后面的部分? . .

The ternary operator is just a weird (or minified) way of saying:三元运算符只是一种奇怪(或缩小)的说法:

if (v == 97 || v == 101 || v == 105 || v==111 || v ==117) {
    a[i] = String.fromCharCode(v); // The character represented by the number v. e.g 97 => 'a'
} else {
    a[i] = v; // The number v without any conversion
}
i++;

Your code is checking for vowels code in an array, if it matches it replaces with the text representation else the number.您的代码正在检查数组中的元音代码,如果匹配,则将其替换为文本表示,否则为数字。

Simplified version of your code (if you understand this )-您的代码的简化版本(如果您理解这一点)-

 let a = [101, 103, 222, 97, 105]; a.forEach(function(v, i){ this[i] = (v == 97 || v == 101 || v == 105 || v==111 || v ==117)? String.fromCharCode(v): v; }, a); console.log(a);

Your code is having - a[i++] = v;}),a;您的代码具有 - a[i++] = v;}),a; I think ,a is referring to the second argument of foreach() loop.我认为,a指的是foreach()循环的第二个参数。

I'd write it like this.我会这样写。 Basically some numbers get replaced with chars.基本上有些数字会被字符替换。

 let a = [101, 103, 222, 97, 105]; for (i = 0; i < a.length; i++) { if ([97, 101, 105, 111, 117].includes(a[i])) { // Replace int with char a[i] = String.fromCharCode(a[i]) } } console.log(a);

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

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