这是一个简单的javascript函数,但由于某种原因,我无法弄清楚为什么未返回预期值。当我在函数中使用console.log()时,它返回期望值,但当我使用return时,它不返回期望值。
var contacts = [
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
}
];
function lookUpProfile(firstName, prop){
contacts.forEach((el) => {
if (el.firstName.toLowerCase() === firstName.toLowerCase()) {
if (el.hasOwnProperty(prop)) {
console.log(el[prop]); //this prints expected value
return el[prop] //why it's not returning any value?
}
}
})
}
lookUpProfile("Sherlock", "likes")
答案 0 :(得分:4)
您仅从forEach
的回调中返回。它没有太大作用。您可以改用find
。这将获得数组中满足回调中提供的条件的第一项。
var contacts=[{"firstName":"Harry","lastName":"Potter","number":"0994372684","likes":["Hogwarts","Magic","Hagrid"]},{"firstName":"Sherlock","lastName":"Holmes","number":"0487345643","likes":["Intriguing Cases","Violin"]}]
function lookUpProfile(firstName, prop){
const found = contacts.find(el => el.firstName.toLowerCase() === firstName.toLowerCase()) || {}
return found[prop]
}
console.log(lookUpProfile("Sherlock", "likes"))
答案 1 :(得分:1)
如果要使用forEach,则需要创建一个空数组,并在满足条件时推送值(以下代码段):
function lookUpProfile(firstName, prop){
const result = [];
contacts.forEach((el) => {
if (el.firstName.toLowerCase() === firstName.toLowerCase()) {
if (el.hasOwnProperty(prop)) {
result.push(el[prop])
}
}
})
return result;
}
MDN的解释:
forEach()对每个数组元素执行一次回调函数;与map()或reduce()不同,它总是返回未定义的值,并且不可链接。典型的用例是在链的末端执行副作用。