如何从JavaScript中删除数组中的特定元素? [英] How do I remove a particular element from an array in JavaScript?
问题描述
我有一个整数数组,我正在使用 .push()
方法向其中添加元素。
是否有一种从数组中删除特定元素的简单方法?相当于 array.remove(int);
。
我必须使用 core JavaScript - 没有框架是允许的。
找到要删除的数组元素的index
,然后使用 splice
。
splice()方法通过删除
现有元素和/或添加新元素来更改数组的内容。
var array = [2,5,9]; console.log(array)var index = array.indexOf(5); if( index> -1){array.splice(index,1);} // array = [2,9] console.log(array);
splice
的第二个参数是要删除的元素数。请注意 splice
修改数组并返回一个包含已删除元素的新数组。
注意:对indexOf的浏览器支持是有限的; Internet和资源管理器7和8不支持它。
如果您在不受支持的浏览器中需要 indexOf
,请尝试以下 polyfill
。查找有关此 <的更多信息em> polyfill
此处 。
Array.prototype.indexOf || (Array.prototype.indexOf = function(d,e){
var a;
if(null == this)抛出新的TypeError('this为null或未定义');
var c = Object(this),
b = c.length>>> 0;
if(0 === b)return -1;
a = + e | | 0;
Infinity === Math.abs(a)&&(a = 0);
if(a> = b)返回-1;
for(a = Math.max(0 <= a?a:b - Math.abs(a),0); a< b;){
if(a& c& c [a] = == d)返回a;
a ++
}
返回-1
});
I have an array of integers, and I'm using the .push()
method to add elements to it.
Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int);
.
I have to use core JavaScript - no frameworks are allowed.
Find the index
of the array element you want to remove, then remove that index with splice
.
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
var array = [2, 5, 9];
console.log(array)
var index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array);
The second parameter of splice
is the number of elements to remove. Note that splice
modifies the array in place and returns a new array containing the elements that have been removed.
Note: browser support for indexOf is limited; it is not supported in Internet Explorer 7 and 8.
If you need indexOf
in an unsupported browser, try the following polyfill
. Find more info about this polyfill
here.
Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
var a;
if (null == this) throw new TypeError('"this" is null or not defined');
var c = Object(this),
b = c.length >>> 0;
if (0 === b) return -1;
a = +e || 0;
Infinity === Math.abs(a) && (a = 0);
if (a >= b) return -1;
for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
if (a in c && c[a] === d) return a;
a++
}
return -1
});
这篇关于如何从JavaScript中删除数组中的特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!