简体   繁体   中英

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:

 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 .

Where is my mistake?

Because your function is returning undefined and you are assigning it to 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

 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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