我正在写一个脚本,我想删除一个名为uniqueWords
的数组的特定元素。我要删除的元素如下:""
," "
和"\n"
。为了达到这个目的,我尝试了:
var removeArray = _.remove(uniqueWords, function (word) {return word === '' || word === ' ' || word === '\n'});
var removeArray2 = _.remove(uniqueWords, function (word) {return _.indexOf(['', ' ', '\n'], word) !== -1});
console.log(removeArray);
console.log(removeArray2);
我正在使用名为loadash的js类,但我得到了以下结果:
["", " ", "↵"]
[]
我的完整代码如下:
<!DOCTYPE html>
<html>
<script src="lodash.js"></script>
<body>
<p id="demo"></p>
<textarea cols=150 rows=15 id="texto">
"RBD|X|RBD|C|92173~GJHGWO.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X|RBD|C|92173~GJHGX4.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X|RBD|C|92173~GJHGX6.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X|RBD|C|92173~GJHGX8.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X|RBD|C|92173~GJHGXA.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X|RBD|C|92173~GJHGXC.NAYE" "SAMBORNSiPOSSSTHRa"
</textarea>
<script>
var splitWords = document.getElementById("texto").value.split(/[["\|~]/);
splitWords = document.getElementById("texto").value.split(/[["\|~]/)
//document.write(splitWords.toString());
uniqueWords = _.uniq(splitWords);
console.log(uniqueWords);
var index = uniqueWords.indexOf("");
var index2 = uniqueWords.indexOf(" ");
var index3 = uniqueWords.indexOf("\n");
console.log(index3)
var arrayLength = uniqueWords.length;
var removeArray = _.remove(uniqueWords, function (word) {return word === '' || word === ' ' || word === '\n'});
var removeArray2 = _.remove(uniqueWords, function (word) {return _.indexOf(['', ' ', '\n'], word) !== -1});
console.log(removeArray);
console.log(removeArray2);
</script>
我想了解实现这一目标的任何建议。
答案 0 :(得分:2)
像这样:
var badList = ['c', 'd'];
var myArray = ['a', 'b', 'c', 'd'];
var removeFromList = function(badlist, arrayToBeFiltered) {
var arrayLength = arrayToBeFiltered.length;
var badArrayLength = badlist.length;
// let's loop through our array that we want to filter
for (var p = 0; p < arrayLength; p++) {
// let's loop through our "bad list"
for (var i = 0; i < badArrayLength; i++) {
var index = arrayToBeFiltered.indexOf(badList[i]);
if (index > -1) {
arrayToBeFiltered.splice(index, 1);
}
}
}
return arrayToBeFiltered;
}
// should return ["a", "b"]
console.log(removeFromList(badList, myArray));
答案 1 :(得分:1)
_.remove()
:正如@elclanrs建议你可以使用id
,但如果你想使用lodash,你可以这样做:
filter
您希望返回数组中不要删除的项目。你正在做相反的事情。
let v = _.remove(uniqueWords, function (word) {return word !== '' && word !== ' ' && word !== '\n'});
let uniqueWords = ['a', 'bravo', '', 'c', ' ', '\n', 'delta', 123];
let removeArray = _.remove(uniqueWords, function(word) {
return word !== '' && word !== ' ' && word !== '\n'
});
console.log(removeArray);
filter()
:您实际上不需要使用lodash来获得您想要的结果。请改用Array.prototype的<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
方法:
filter()