2016-10-07 44 views
0

我想寫一個函數,使用reduce()方法來計算數組中的項目數並返回該數組的長度。使用函數時獲取未定義

這是我到目前爲止有:

function len(items) { 
    items.reduce(function(prev, curr, index){ 
     return index+1; 
    }); 
} 

let nums = [1, 2, 3]; 

console.log(len(nums)); 

每當我嘗試運行此代碼,在我的瀏覽器控制檯,我得到「未定義」的消息。我想我定義了我的功能,所以我不知道爲什麼它沒有被調用或輸出任何值。請讓我知道我做錯了什麼,或者我的邏輯錯誤。

回答

2

你忘記返回

function len(items) { 
    return items.reduce(function(prev, curr, index){ 
     return index+1; 
    }); 
} 

或者乾脆

function len(items) { 
    return items.length; 
} 
+0

我需要使用reduce才能獲得長度。 – FlameDra

+0

@flamedra然後你可以選擇我提到的第一個選項。 – gurvinder372

2

function len(items) { 
 
    return items.reduce(function(prev, curr, index){ 
 
     return index+1; 
 
    }); 
 
} 
 

 
let nums = [1, 2, 3]; 
 

 
console.log(len(nums));

+0

這是行得通的。你能解釋一下當我還在函數中返回時,是否需要返回reduce方法嗎? – FlameDra

0

試試這個:

function len(items) { 
    if(items){     //error handle 
    return items.length; 

    } 
     return 0; 
} 
+0

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

+0

我需要使用reduce方法來獲得長度。 – FlameDra

相關問題