我正在完成一项任务并且不需要这样做,但我希望进一步了解。我需要删除任何在此列表中删除的内容。
var sentence = ["REMOVE","Today","I'm","REMOVE","excited","to","learn","REMOVE","REMOVE","about","arrays"];
console.log("Original Sentence: " + sentence);
// Your code goes here
console.log("Final Sentence: " + sentence);

我是这样做的,而不是删除" REMOVE",它显示每次发生删除。我如何让它做与目前正在做的相反的事情。
var sentence = ["REMOVE","Today","I'm","REMOVE","excited","to","learn","REMOVE","REMOVE","about","arrays"];
console.log("Original Sentence: " + sentence);
// Your code goes here
function filterItems(query) {
return sentence.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}
var test = filterItems('re');
console.log("Fixed sentence" +test);

答案 0 :(得分:0)
您正在过滤包含查询的项目,您只需更正过滤逻辑。
var sentence = ["REMOVE","Today","I'm","REMOVE","excited","to","learn","REMOVE","REMOVE","about","arrays"];
console.log("Original Sentence: " + sentence);
// Your code goes here
function filterItems(query) {
return sentence.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) == -1;
})
}
var test = filterItems('re');
console.log("Fixed sentence" +test);

答案 1 :(得分:0)
你的逻辑是倒退的。 Array#filter
返回一个包含满足谓词的元素的新数组。你的谓词现在是"包含单词REMOVE"。
你想要反转(用> -1
字面替换< 0
):
var sentence = ["REMOVE","Today","I'm","REMOVE","excited","to","learn","REMOVE","REMOVE","about","arrays"];
console.log("Original Sentence: " + sentence);
// Your code goes here
function filterItems(query) {
return sentence.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) < 0;
})
}
var test = filterItems('re');
console.log("Fixed sentence" +test);
&#13;
答案 2 :(得分:0)
.filter
创建了一个新数组,并且没有修改现有数组,我建议使用.splice
代替......除非你打算重新使用原来的{{1}再次并期望它拥有它的原始值
这样的事情应该有效
sentence
&#13;
答案 3 :(得分:0)
检查有关如何使用过滤方法的链接。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var sentence =["REMOVE","Today","I'm","REMOVE","excited","to","learn","REMOVE","REMOVE","about","arrays"];
console.log("Original Sentence: " + sentence);
var test = sentence.filter(word => word.toLowerCase() !== "remove");
console.log("Fixed sentence: " + test);
&#13;