简体   繁体   English

为什么使用 JavaScript 的 find() 方法返回未定义?

[英]Why does this use of JavaScript's find() method return undefined?

I ran into this (unexpected) bug while trying to make a JavaScript function that gets a single post by id, from an array of objects:我在尝试制作 JavaScript function 时遇到了这个(意外的)错误,它通过 id 从对象数组中获取单个帖子:

 let posts = [ {id: 1, title: "Lorem ipsum dolor sit amet"}, {id: 2, title: "Numquam natus culpa non dignissimos dicta"}, {id: 3, title: "Tenetur culpa accusamus"} ]; let singlePost; function findById(array, id) { singlePost = array.find(function(post){ console.log(post.id); return post.id === id; }); } singlePost = findById(posts, 2); console.log(singlePost);

For a reason I have not figured out, console.log(singlePost) outputs undefined .出于某种原因,我还没有弄清楚, console.log(singlePost)输出undefined

Where is my mistake?我的错误在哪里?

Because your function is returning undefined and you are assigning it to singlePost .因为您的 function 返回undefined并且您将其分配给singlePost You can check below.你可以在下面检查。

findById(posts, 2);
console.log(singlePost); // This will console.log the value of singlePost

You are setting a variable without the function returning anything, so replace the assignment of the variable within the function with a return您正在设置一个没有 function 返回任何内容的变量,因此将 function 中的变量分配替换为返回

 let posts = [ {id: 1, title: "Lorem ipsum dolor sit amet"}, {id: 2, title: "Numquam natus culpa non dignissimos dicta"}, {id: 3, title: "Tenetur culpa accusamus"} ]; let singlePost; function findById(array, id) { return array.find(function(post){ return post.id === id; }); } singlePost = findById(posts, 2); console.log(singlePost);

Of course, the function was not returning the singlePost itself.当然,function 本身并没有返回singlePost Here is what I should have done:这是我应该做的:

 let posts = [ {id: 1, title: "Lorem ipsum dolor sit amet"}, {id: 2, title: "Numquam natus culpa non dignissimos dicta"}, {id: 3, title: "Tenetur culpa accusamus"} ]; let singlePost; function findById(array, id) { singlePost = array.find(function(post) { return post.id === id; }); return singlePost; } singlePost = findById(posts, 2); console.log(singlePost);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM