2015-12-18 75 views
1
//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 

我想在TypeScript中使用新的「of」循環。 但是,沒有按照我的預期工作。例如,在最後一次嘗試中,當我預計得到14時,我得到「NaN」值。 我做錯了什麼?如何在TypeScript中使用for ...循環?

+0

對不起,我在第一次嘗試中增加了下面的內容: –

+0

let result:number = add(1,5,8); document.body.innerHTML ='Result = $ {result}'; //結果= 14 –

+0

難道你不是指'temp + = i;'? –

回答

4

for (... of ...)的語法產生陣列而不是它們的指數實際的元件。因此,正確的JavaScript語法很簡單:

function add(...numbers) { 
    let sum = 0; 
    for (let i of numbers) { 
     sum += i; 
    } 
    return sum; 
} 

(添加類型註釋獲得打字稿。)

當然,因爲numbers是一個數組ES6還允許您用一行代碼做到這一點:

add = (...numbers) => numbers.reduce((x, y) => x + y, 0) 
+0

非常感謝CR。現在很好用:) –