我有一个包含字符串的数组,我需要删除包含某个字符串的每个元素。
var arr = ["abc", "123", "dfg", "bbb"];
var string = "b"
删除包含字符串的任何元素后,数组应如下所示:
["123", "dfg"];
答案 0 :(得分:4)
与Array.prototype.filter
相关:
var arr = ["abc", "123", "dfg", "bbb"];
var string = "b";
alert(arr.filter(function (i) { return i.indexOf(string) < 0 }))
&#13;
答案 1 :(得分:0)
您可以简单地遍历数组并收集所有不包含该字符串的项目
您可以使用String is [ABCDEFGHIJK#]
Position is [4096], string is [ABCDEFGHIJK#], character is []
Position is [2048], string is [ABCDEFGHIJK#], character is []
Position is [1024], string is [ABCDEFGHIJK#], character is []
Position is [512], string is [ABCDEFGHIJK#], character is []
Position is [256], string is [ABCDEFGHIJK#], character is []
Position is [128], string is [ABCDEFGHIJK#], character is []
Position is [64], string is [ABCDEFGHIJK#], character is []
Position is [32], string is [ABCDEFGHIJK#], character is []
Position is [16], string is [ABCDEFGHIJK#], character is []
Position is [8], string is [ABCDEFGHIJK#], character is [I]
Found char, len is [8], string is now [IJK#]
Position is [4], string is [IJK#], character is []
Position is [2], string is [IJK#], character is [K]
Found char, len is [10], string is now [K#]
Position is [1], string is [K#], character is [#]
Found char, len is [11], string is now [#]
11
函数查找一个字符串出现在另一个字符串中。
indexOf
&#13;
请注意,我添加了 var arr = ["abc", "123", "dfg", "bbb"];
var string = "b";
var result = [];
for (var i = 0; i < arr.length; i++)
{
if (arr[i].indexOf(string) === -1)
{
result.push(arr[i]);
}
}
document.body.innerHTML = result;
行以显示结果。在您的代码中使用之前不要忘记删除它:)
答案 2 :(得分:0)
您也可以使用Array.prototype.splice方法,请检查以下摘录。
var arr = ["abc", "123", "dfg", "bbb"];
var string = "b";
arr.splice(1,1);
document.getElementById("ans").value = arr[1];
&#13;
<input id='ans' type='text'>
&#13;