繁体   English   中英

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

[英]JavaScript - Cannot read property 'toLowerCase' of undefined

找不到问题,但是一直显示这个错误!! 使用其他方法(如包含)时也会发生同样的情况。

 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() === ...

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

最有可能的是,您想远离空的大括号对。

有一个没有属性title的对象,因此您会收到该错误。 它是这样的:

undefined.toLowercase()
        ^

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

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

在将倾斜和正文转换为小写之前,您需要提供空检查。

 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)

从数组中删除一个空的 '{}' 对象,note.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'
}]

更新您的过滤器方法以检查键是否存在,然后匹配其他返回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()

笔记

  • 在访问 toLowerCase 属性之前首先检查 field.label

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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