JavaScript - 无法读取未定义的属性'toLowerCase'



找不到问题,但它一直显示此错误!!当使用includes等其他方法时也会发生同样的情况。

let notes = [{},{
title: 'My next trip',
body: 'I would like to go to Spain'
},{
title: 'Habits to work on',
body: 'Exercise. Eating a bit better'
},{
title: 'Office modification',
body: 'Get a new seat'
}]
let filteredNotes = notes.filter( function (note, index) {
let findFileredTitle = note.title.toLowerCase().includes('ne')
let findFileredBody = note.body.toLowerCase().includes('ne')
return findFileredTitle || findFileredBody
})
console.log(filteredNotes)

您的数组注释包含四个元素。第一个是空的。看到那对空牙套了吗?

let notes = [{}, {

稍后访问时:

note.title.toLowerCase() === ...

然后注意.title未定义,您会收到错误消息。

最有可能的情况是,您想要远程传输空的大括号。

有一个对象没有属性title,因此会出现错误。它有点像:

undefined.toLowercase()
^

您可以在note.title上添加一个检查部件,如下所示:

note.title && (note.title.toLowercase() === .........)
^ 

更新您的筛选方法以检查键是否存在,然后进行匹配其他返回false

let filteredNotes = notes.filter( function (note, index) {
let findFileredTitle = note.title && note.title.toLowerCase().includes('ne')
let findFileredBody = note.body && note.body.toLowerCase().includes('ne')
return findFileredTitle || findFileredBody
});

问题:错误错误:未捕获(承诺中(:类型错误:field.label是未定义的

解决方案

field.label && field.label.toLowerCase()

注意

  • 访问LowerCase属性之前,首先检查field.label

在将tilte和body转换为小写之前,需要提供null检查。

let notes = [{},{
title: 'My next trip',
body: 'I would like to go to Spain'
},{
title: 'Habits to work on',
body: 'Exercise. Eating a bit better'
},{
title: 'Office modification',
body: 'Get a new seat'
}]
let filteredNotes = notes.filter(function (note, index) {
let findFileredTitle = '';
if(note.title){
findFileredTitle = note.title.toLowerCase().includes('ne')
}
let findFileredBody = '';
if(note.body){
findFileredBody = note.body.toLowerCase().includes('ne');
}
return findFileredTitle || findFileredBody
})
console.log(filteredNotes)

从数组中删除一个空的"{}"对象,注意.title为null/empty,因此返回错误

let notes = [{
title: 'My next trip',
body: 'I would like to go to Spain'
},{
title: 'Habits to work on',
body: 'Exercise. Eating a bit better'
},{
title: 'Office modification',
body: 'Get a new seat'
}]

最新更新