arrays - NodeJs笔记应用程序删除功能不起作用?

标签 arrays node.js

我正在构建一个 Nodejs Note 应用程序,我对此很陌生,所以这里的删除功能不起作用,它会删除数组中的所有内容,我只想删除标题 有两个文件app.js和note.js。

这是app.js文件的内容

if (command === "add") {
    var note = notes.addNote(argv.title, argv.body);
    if (note) {
        console.log("Note created");
        console.log("__");
        console.log(`Title: ${note.title}`);
        console.log(`Body: ${note.body}`);
    } else {
        console.log("The title has already exist")
    }
} else if (command === "delete") {
    var noteRemoved = notes.delNote(argv.title)
    var message = noteRemoved ? "Note has been removed" : "Note not found";
    console.log(message)
}

这是 note.js 内容

var fetchNotes = function () {
    try {
        var noteString = fs.readFileSync("notes-data.json")
        return JSON.parse(noteString);
    } catch (e) {
        return [];
    }
};

var saveNotes = function (notes) {
    fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};

var addNote = function (title, body) {
    var notes = fetchNotes();
    var note = {
        title,
        body
    };

    var duplicateNotes = notes.filter(function (note) {
        return note.title === title;

    });

    if (duplicateNotes.length === 0) {
        notes.push(note);
        saveNotes(notes);
        return note;
    };
}

var delNote = function (title) {
    var notes = fetchNotes();
    var filteredNotes = notes.filter(function (note) {
        note.title !== title;
    });
    saveNotes(filteredNotes);
    return notes.length !== filteredNotes.length
}

最佳答案

您错过了 delNote 过滤函数中的 return 语句

var filteredNotes = notes.filter(function (note) {
    return note.title !== title;
});

或者我们可以使用 es6 语法:

const filteredNotes = notes.filter(note => note.title !== title);

关于arrays - NodeJs笔记应用程序删除功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49346759/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

javascript - 使用 for 循环中的拼接从数组中删除项目

javascript - 如何使用 Jison 生成处理语法歧义的解析器?

node.js - 无法使用无服务器框架和 TypeScript 从 Lambda 层导入模块

css - 使用 Grunt 和 grunt-contrib-cssmin 删除注释

node.js - require.js 下的并行 javascript 缩小,使用 Node ?

javascript - 是否可以在Android中编写一个生成两个数组的函数

jquery数组到eq函数

ios - 如何从 UITableView 中的数组中获取用户选择的值并将该值传递给服务器

linux - 如何选择我的 npm 路径?