使用javascript过滤和删除列表中的项目

时间:2018-01-17 19:26:14

标签: javascript

我正在完成一项任务并且不需要这样做,但我希望进一步了解。我需要删除任何在此列表中删除的内容。



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);




4 个答案:

答案 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):

&#13;
&#13;
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;
&#13;
&#13;

答案 2 :(得分:0)

.filter创建了一个新数组,并且没有修改现有数组,我建议使用.splice代替......除非你打算重新使用原来的{{1}再次并期望它拥有它的原始值

这样的事情应该有效

&#13;
&#13;
sentence
&#13;
&#13;
&#13;

答案 3 :(得分:0)

检查有关如何使用过滤方法的链接。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

&#13;
&#13;
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;
&#13;
&#13;