有没有一种快速的方法从Javascript中删除数组中的特定值?

时间:2010-09-22 22:31:42

标签: javascript arrays

我有一个数组

var array = ["google","chrome","os","windows","os"];

我想从数组中删除值"chrome"而不将数组变为字符串。有没有办法做到这一点?

6 个答案:

答案 0 :(得分:5)

没有比找到它然后删除它更快的方法。找到它你可以用循环或(在支持它的实现中)indexOf。删除它可以使用splice

实例:http://jsbin.com/anuta3/2

var array, index;
array = ["google","chrome","os","windows","os"];
if (array.indexOf) {
  index = array.indexOf("chrome");
}
else {
  for (index = array.length - 1; index >= 0; --index) {
    if (array[index] === "chrome") {
      break;
    }
  }
}
if (index >= 0) {
  array.splice(index, 1);
}

答案 1 :(得分:3)

这将它包装成一个方便的功能:

function remove_element(array, item) {
  for (var i = 0; i < array.length; ++i) {
    if (array[i] === item) {
      array.splice(i, 1);
      return;
    }
  }
}

var array = ["google", "chrome", "os", "windows", "os"];
remove_element(array, "chrome");

或(对于支持indexOf的浏览器):

function remove_element(array, item) {
  var index = array.indexOf(item);
  if (-1 !== index) {
    array.splice(index, 1);
  }
}

修改:修正了===!==

答案 2 :(得分:2)

使用Array类的splice方法。

array.splice(1, 1);

答案 3 :(得分:2)

splice()方法在数组中添加和/或删除元素,并返回已删除的元素。

array.splice(indexOfElement,noOfItemsToBeRemoved);

在你的情况下

   array.splice(1, 1);

答案 4 :(得分:2)

You may want to remove all of the items that match your string,
or maybe remove items that pass or fail some test expression.
Array.prototype.filter, or a substitute, is quick and versatile: 


var array= ["google","chrome","os","windows","os"],
b= array.filter(function(itm){
    return 'os'!= itm
});
alert(b)

答案 5 :(得分:1)

您没有提及是否需要保留数组中其余元素的索引。在您可以处理数组的未定义成员的基础上,您可以执行以下操作:

var array = ["google","chrome","os","windows","os"];
delete array[1];

数组[1]将是未定义的。