//No issues in below:
let a = [1, 2, 3, 4, 5];
for (let i of a) {
document.write('<br />' + i); //1 2 3 4 5
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//No issues in below either
function add(...numbers: number[]): number {
let temp: number = 0;
for (var i: number = 0; i < numbers.length; i++) {
temp += numbers[i];
}
return temp;
}
let result: number = add(1,5,8);
document.body.innerHTML = `Result = ${result}`; //Result = 14
// +++++++++++++++++++++++++++++++++++++++++++++++++
// Hmm! Undefined
function add(...numbers: number[]): number {
let temp: number = 0;
for (let i of numbers) {
temp += numbers[i];
}
return temp;
}
let result: number = add(1,5,8);
document.body.innerHTML = `Result = ${result}`; // Result = NaN
我正在尝试使用#34;&#34; forScript中的for循环。 但是,没有像我预期的那样工作。例如,在最后一次尝试中我得到了&#34; NaN&#34;当我被期望获得14时的价值。 我做错了什么?
答案 0 :(得分:4)
for (... of ...)
语法产生数组的实际元素,而不是索引。因此,正确的JavaScript语法就是:
function add(...numbers) {
let sum = 0;
for (let i of numbers) {
sum += i;
}
return sum;
}
(添加类型注释以获取TypeScript。)
当然,由于numbers
是一个数组,因此ES6也允许你用单行代码执行此操作:
add = (...numbers) => numbers.reduce((x, y) => x + y, 0)