javascript - 为什么 "!duplicateNote.length"不工作?

标签 javascript arrays node.js object ecmascript-6

我正在使用 yargs 创建一个通过命令行访问的笔记应用程序。当我输入一个新标题时,它应该检查并确保与输入的标题相似的标题不存在以避免重复。因此,如果没有重复项,理论上它应该求值为 !duplicateNote.length,因为里面什么都没有。

但是, undefined object 导致我的应用程序中断,而它曾经可以正常工作。我想不通。一切都已正确要求。

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

最佳答案

因为如果没有任何东西可以找到,您将得到undefined。如果要检查,请使用 filter

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

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

关于javascript - 为什么 "!duplicateNote.length"不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56519206/

相关文章:

javascript - Express路由器发布功能不起作用

javascript - 在需要 Node 模块时强制执行区分大小写的字符串匹配

node.js - 在 Cloud9 IDE(容器)中使用 Vue CLI : 'Invalid Host Header'

javascript - XMLHttpRequest 发送文件请求对于大文件给出 404 错误

PHP关键字函数在合并两个数组后中断

c++ - double 随机数数组

javascript - 初始化多维数组的循环/递归方法

javascript - 异步退出 Node 域的问题

javascript - 在 d3js 中用(动画)路径连接点

javascript - 在测试 JavaScript 时,有什么比 setTimeout 更好的等待异步回调的方法吗?