studentList[
{
name:"A",
id:1
},
{
name:"B",
id:2
},
{
name:"C",
id:3
}
]
现在要从学生表(studentList)中获取到id为2的对象的name,
这边不使用循环,直接推荐使用find方法。
var res = this.studentList.find(item => item.id === 2)
console.log(res.name)
但是在页面上渲染数据的时候遇到了一个挺坑爹的报错:

TypeError: Cannot read property ‘name’ of undefined
解决方法<—通过这个大佬的文章终于解决了问题。(以下是个人理解,经供参考)find方法会依次检验item是否与判定值相等,如果不相等,它也会返回一个undefined,同时res接收到了这个undefined,在被渲染就会报错。所以解决方法为在外面加一层判断:
getCourseTimeType(courseTime){
var res = this.CourseTimeList.find(item => item.value == courseTime)
if(res){
return res.name
}
}
文章讲述了如何在JavaScript中使用`find`方法从`studentList`中非循环获取id为2的学生对象,以及在遇到`TypeError:Cannotreadpropertynameofundefined`错误时的解决方案,即在`find`后添加判断条件以防止渲染时的undefined问题。


&spm=1001.2101.3001.5002&articleId=135415271&d=1&t=3&u=561a89c4074d465dbc2b147dd29077b2)
995

被折叠的 条评论
为什么被折叠?



