2016-10-07 114 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

相关问题