簡體   English   中英

JavaScript find() 方法搜索對象數組以查找元素,結果不可訪問

[英]JavaScript find() method searches through an array of objects to find an element, the outcome not accessible

 //array of objects
 const posts = [ {userId: 1, id: 1, title: "sunt", author: 
 "Tom"},
 {userId: 1, id: 2, title: "qui est esse",author: "Tom"},
 {userId: 1, id: 3, title: "ea molestias", author: "Tom"}, 
 {userId: 1, id: 4, title: "eum et est occaecati", author: 
 "Tom"}]

 //id of one of the object
 const ItemId = 2

 //trying to find the object that has id: 2 an then print other 
 key -values pairs from that prticular object

 let post= posts.find(item=> item.id===ItemId)
 console.log(post)
 //result: {userId: 1, id: 2, title: "qui est esse",author: 
 "Tom"}
 console.log(post.title)
 //result: undefined --- why can not access these properties?
 console.log(post.author)
 //result: undefined
 console.log (typeof post)
 //result:  "string" --- why string, its an object is it?

  

感謝任何見解,我不明白為什么那些 find() 方法的結果不能通過我們訪問對象中的屬性的方式來訪問? 我也嘗試過使用這樣的括號: post[author) 沒有成功......非常感謝關於這個主題的任何事情

你沒有收到任何錯誤嗎? 因為當我復制您的代碼並運行時,它有多個錯誤。

//array of objects
const posts = [ {userId: 1, id: 1, title: "sunt", author: "Tom"},
{userId: 1, id: 2, title: "qui est esse",author: "Tom"},
{userId: 1, id: 3, title: "ea molestias", author: "Tom"}, 
{userId: 1, id: 4, title: "eum et est occaecati", author: 
"Tom"}];
let post= posts.find(item=> item.id===2)
console.log(post)
console.log(post.title)
console.log(post.author)
console.log (typeof post)

試試這個代碼。 它正在返回正確的一切

您的代碼似乎有幾個語法錯誤:

首先,您忘記在數組中的一個元素之后放置逗號。 每個元素應該用逗號分隔{userId: 1, id: 2, title: "qui est esse",author: "Tom"},

Javascript 中的局部變量可以使用=符號設置值。 在您的代碼中,您使用的是const ItemId: 2 使用:聲明變量僅應在 Object 中聲明時使用,但在聲明局部變量或常量時不應使用。

這是具有固定語法錯誤的完整代碼:

 //array of objects
 const posts = [ {userId: 1, id: 1, title: "sunt", author: 
 "Tom"},
 {userId: 1, id: 2, title: "qui est esse",author: "Tom"},
 {userId: 1, id: 3, title: "ea molestias", author: "Tom"}, 
 {userId: 1, id: 4, title: "eum et est occaecati", author: 
 "Tom"}];

 //id of one of the object
 const ItemId = 2;

 //trying to find the object that has id: 2 an then print other  key -values pairs from that prticular object

 let post= posts.find(item=> item.id===ItemId)
 console.log(post)
 //result: {userId: 1, id: 2, title: "qui est esse",author: "Tom"}
 console.log(post.title)
 //result: undefined --- why can not access these properties?
 console.log(post.author)
 //result: undefined
 console.log (typeof post)
 //result:  "string" --- why string, its an object is it?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM