我在notes.json
文件中有一个元素数组,使用filter
方法删除它们时遇到问题。
以下是我从 json 文件中读取注释的方式:
const fs = require("fs");
const path = require("path");
const p = path.join(path.dirname(process.mainModule.filename),"data","notes.json");
// this function help me do fast code
const fastFunction = cb => {fs.readFile(p, (err, data) => {if (err) {return cb([]);} else {return cb(JSON.parse(data));}});};
我在另一个removeById
中使用此fastFunction
,如下所示:
static removeById(id) {fastFunction(notes => {const deleteNote = notes.filter(n => n.id !== id);fs.writeFile(p, JSON.stringify(deleteNote), err => {if (err) {console.log(`Your Error Is: ${err}`);}});});}
最后,这是我尝试使用removeById
函数的方式。
// here i used the function
const postDeleteNotes = (req, res, next) => {
const myId = req.body.removeById;Note.removeById(myId);res.redirect("/admin");
};
但是,如果我删除纸条并尝试再次获取它们,它仍然存在。
我可能做错了什么?
我在这里找到了一个更奇怪的解决方案:
我改变这个:
n => n.id !== id
对此:n => n.id != id
阅读评论后,我认为您的代码是这样的:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(arr.filter(i => i < 3 || i > 5));
// [1, 2, 6, 7, 8, 9, 10]
但回头看arr[4]
给出 5,因为filter
函数不会影响原始数组。而是返回修改后的数组。因此,如果要修改原始数组,则需要执行分配。
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr = arr.filter(i => i < 3 || i > 5);