如何解决JavaScript find() 方法搜索对象数组以查找元素,结果不可访问
//array of objects
const posts = [ {userId: 1,id: 1,title: "sunt",author:
"Tom"},{userId: 1,id: 2,title: "qui est esse",author: "Tom"},id: 3,title: "ea molestias",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,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",id: 3,title: "ea molestias",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,
Javascript 中的局部变量可以使用 =
符号设置一个值。在您的代码中,您使用了 const ItemId: 2
。使用 :
声明变量只应在对象内部声明时使用,而不能在声明局部变量或常量时使用。
这是修复了语法错误的完整代码:
//array of objects
const posts = [ {userId: 1,author:
"Tom"},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,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?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。