为什么“!duplicateNote.length”不起作用?

时间:2019-06-09 23:58:47

标签: javascript arrays node.js object ecmascript-6

我正在使用yargs创建通过命令行访问的笔记应用程序。输入新标题时,应该检查并确保没有像输入的标题那样的标题,以避免重复。因此,如果没有重复项,则理论上应该评估为!duplicateNote.length,因为其中没有任何内容。

但是,未定义的对象导致我的应用程序中断,而该应用程序曾在该处运行。我不知道。一切都已正确要求。

APP.JS文件

yargs.command({
    command: 'add',
    describe: 'Add a new note',
    builder: {
        title: {
            describe: 'Note title',
            demandOption: true,
            type: 'string'
        }, 
        body: {
            describe: 'Note body',
            demandOption: true,
            type: 'string'
        }
    },
    handler(argv) {
        notes.addNote(argv.title, argv.body)
    }
})  

NOTES.JS文件

const addNote = (title, body) => {
    const notes = loadNotes()
    const duplicateNote = notes.find((note) => note.title === title)

    if (!duplicateNote.length) {
        notes.push({
            title: title,
            body: body
        })
        saveNotes(notes)
        console.log(chalk.green.inverse('New note added!'))
    } else {
        console.log(chalk.bgRed('Note title taken!'))
    }
}

const loadNotes= () => {
    try {
        const dataBuffer = fs.readFileSync('notes.json')
        const dataJSON = dataBuffer.toString()
        return JSON.parse(dataJSON)
    } catch (e) {
        return[]
    }

}

module.exports = {
    addNote:    addNote,
    removeNote: removeNote,
    listNotes:  listNotes,
    readNote:   readNote
}

我希望“已添加新注释!”记录到控制台,但我得到:TypeError: Cannot read property 'length' of undefined

1 个答案:

答案 0 :(得分:0)

因为find一无所有,您得到undefined。如果要检查,请使用filter

const duplicateNote = notes.filter((note) => note.title === title)

filter始终给出一个数组-find给出undefined或找到的任何数据类型。

相关问题