是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]
其他回答
另一个变化:
if (!Array.prototype.removeArr) {
Array.prototype.removeArr = function(arr) {
if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
var that = this;
if(arr.length){
var i=0;
while(i<that.length){
if(arr.indexOf(that[i])>-1){
that.splice(i,1);
}else i++;
}
}
return that;
}
}
它又是循环中的indexOf(),但前提是要删除的数组相对于要清理的数组较小;每次移除都会缩短while循环。
ES6路。
const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);
在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf(item);//item: the value which you want to remove
//Method 1
ary.splice(index,1);
//Method 2
delete ary[index]; //in this method the deleted element will be undefined
你可以像这样使用indexOf方法:
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
注意:对于IE8及以下版本,您需要对其进行填充
Var数组= [1,2,3,4] Var项= 3 var index = array.indexOf(item); 数组中。拼接(指数(1); console.log(数组)
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]