【发布时间】:2019-01-20 11:18:07
【问题描述】:
我有一个对象数组,我正在尝试根据用户传递的参数删除特定项目,
removeItem = (title, body){
let myArray = [
{ title : 'title 1', body: 'body of title one' },
{ title : 'title 2', body: 'body of title two' },
{ title : 'title 3', body: 'body of title three' },
]
//the problem is down here
let filteredArray = myArray.filter(item => {
item.title != title || item.body != body
}
// at this point i assume that the filtered array will not
// include the item that i want to remove
// so down here i reset the value of my original array to the filtered one
myArray = filteredArray
简单来说,我要运行的测试是, 如果用户的标题或正文与数组中的标题或正文不匹配,则将此项目放入一个新数组中,因此我将有一个过滤数组..
然而,发生的事情是,上面的代码删除了一切并返回一个空数组。 有人可以帮助纠正上面的逻辑吗? 提前致谢
【问题讨论】:
-
过滤函数需要返回一个布尔值,如果你想“保持”它为true,则将其删除。所以你的代码应该是
return item.title != title || item.body != body -
代码没有运行
标签: javascript arrays node.js