我一直在尝试编写代码,将数组的偶数索引元素乘以 2,将奇数索引元素乘以 3。
我在变量 number 中存储了以下数字,它表示一个数字数组
numbers = [1,7,9,21,32,77];
Even Indexed Numbers - 1,9,32
Odd Indexed Numbers - 7, 21, 77
请记住,数组是零索引的,这意味着编号从 0 开始。在这种情况下,索引为 0 的元素实际上是 1,索引为 1 的元素是 7。
这是我期望的输出结果
[2,21,18,63,64,231]
不幸的是,我得到了这个输出
[2,14,17,42,64,154]
这是我的方法的代码
numbers = numbers.map(function(x) {
n = 0;
while (n < numbers.length) {
if (n % 2 == 0) {
return x * 2;
}
else {
return x * 3;
}
n++;
}});
return numbers;
我在这里创建了一个 while 循环,它为变量 n 的每次迭代执行代码。对于变量 n 的每个值,我检查 n 是否为偶数,代码 n % 2 == 0 使用它。虽然 0 % 2 == 0 是真的,但 1 % 2 == 0 不是真的.我在 while 循环结束时递增 n,所以我不明白为什么我收到了我所做的输出。
我们将不胜感激。
最佳答案
您创建了一个名为 n
的全局属性,方法是
n = 0;
然后,
while (n < numbers.length) {
if (n % 2 == 0) {
return x * 2;
} else {
return x * 3;
}
}
n++; // Unreachable
你总是马上回来。因此,n++
永远不会递增。因此,n
始终保持为 0,因此所有元素始终乘以 2
。
Array.prototype.map
的回调函数,第二个参数是索引本身。所以,map
的正确使用方法是这样的
numbers.map(function(currentNumber, index) {
if (index % 2 === 0) {
return currentNumber * 2;
} else {
return currentNumber * 3;
}
});
同样可以写得简洁,用三元运算符,像这样
numbers.map(function(currentNumber, index) {
return currentNumber * (index % 2 === 0 ? 2 : 3);
});
关于JavaScript - 将偶数索引数组元素乘以 2 并将奇数索引数组元素乘以 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26552694/