如何对元素执行条件pop()

时间:2014-10-29 18:27:26

标签: javascript arrays

我有一个元素,我需要从数组中弹出,比如说:

arr = [1, 2 , 3, 4, 5]
if (value === 3){
 arr.pop() // so if the value is '3', I'd like to pop that record from the array, and record could be anywhere between, after or before in a list of array.

这可能吗?

2 个答案:

答案 0 :(得分:3)

您可以使用splice方法执行此操作。

var ind = arr.indexOf(3);
if(ind != -1) {
  arr.splice(ind, 1);
}

答案 1 :(得分:0)

您可以使用filter method创建一个没有项目的数组:

arr = arr.filter(function(v){ return v != 3; });

即使它在数组中出现多次,也会删除该值。

(请注意文档中的兼容性信息。filter方法并非在所有浏览器中都可用,例如IE 8。)