使用 for of 循环计算数组中的多个元素
Use a for of loop to calculate multiply elements in an array
我是 JavaScript 的新手,我有一个关于 for...of
的练习,但它失败了。它返回 NaN
.
我哪里做错了,我需要什么?
代码:
var arr = [];
function multiply(arr) {
for (var a of arr) {
a *= arr[a];
}
return a;
}
console.log(multiply([2, 3, 4])); // expect: 24
请参阅下面修改的代码。正在工作:
var arr = undefined;
function multiply(arr) {
if (!arr || !arr.length) { // if the array is undefined or has no elements, return null
return null;
} // otherwise, continue to do the calculation, it's an array with values
var result = 1; // start our result in 1
for (var a of arr) {
result *= a; // increase the result by multiplying the
// previous value for every value in the array
}
return result; // finally return
}
console.log(multiply([2, 3, 4])); // expect: 24
console.log(multiply([])); // expect: null: 0 elements
console.log(multiply(arr)); // expect: null: arr var is undefined
console.log(multiply()); // expect: null: no argument provided
我是 JavaScript 的新手,我有一个关于 for...of
的练习,但它失败了。它返回 NaN
.
我哪里做错了,我需要什么?
代码:
var arr = [];
function multiply(arr) {
for (var a of arr) {
a *= arr[a];
}
return a;
}
console.log(multiply([2, 3, 4])); // expect: 24
请参阅下面修改的代码。正在工作:
var arr = undefined;
function multiply(arr) {
if (!arr || !arr.length) { // if the array is undefined or has no elements, return null
return null;
} // otherwise, continue to do the calculation, it's an array with values
var result = 1; // start our result in 1
for (var a of arr) {
result *= a; // increase the result by multiplying the
// previous value for every value in the array
}
return result; // finally return
}
console.log(multiply([2, 3, 4])); // expect: 24
console.log(multiply([])); // expect: null: 0 elements
console.log(multiply(arr)); // expect: null: arr var is undefined
console.log(multiply()); // expect: null: no argument provided