Reputation: 13
//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
I am trying to use new "of" for loops in TypeScript. However, not working as I expected. For example, in last try I am getting "NaN" value when I was expected to get 14. What I am doing wrong?
Upvotes: 1
Views: 915
Reputation: 9817
The for (... of ...)
syntax yields the actual elements of the array and not their indices. Therefore the proper JavaScript syntax is simply:
function add(...numbers: number[]): number {
let sum = 0;
for (const i of numbers) {
sum += i;
}
return sum;
}
Of course, since numbers
is an array ES6 also allows you to do this with the one-liner:
const add = (...numbers: number[]) => numbers.reduce((x, y) => x + y, 0);
In fact in terms of performance, the latter might be slightly more easy for the VM to optimize, although the VM might not optimize it until add()
has been called many times and determined to be a hotspot in the code. But of course your decision about which you adopt depends on whether you have a team who is comfortable with folds like the above.
Upvotes: 4