在数组元素上使用delete运算符与使用array.splice方法有什么区别?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?
在数组元素上使用delete运算符与使用array.splice方法有什么区别?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?
当前回答
如果您的阵列较小,可以使用过滤器:
myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');
其他回答
IndexOf也接受引用类型。假设以下场景:
var arr=[{项:1},{项2},{项3}];var发现=发现(2,3)//伪代码:将返回〔{item:2},{item:3}〕var l=基础长度;而(l-){var索引=arr.indexOf(找到[l])arr.splice(索引,1);}控制台日志(arr.length)//1.
不同之处:
var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
while(!found && l--) {
found = arr[l] === item2;
}
console.log(l, arr[l]);// l is index, arr[l] is the item you look for
因为delete只从数组中的元素中删除对象,所以数组的长度不会改变。拼接将删除对象并缩短阵列。
以下代码将显示“a”、“b”、“undefined”、“d”
myArray = ['a', 'b', 'c', 'd']; delete myArray[2];
for (var count = 0; count < myArray.length; count++) {
alert(myArray[count]);
}
而这将显示“a”、“b”、“d”
myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);
for (var count = 0; count < myArray.length; count++) {
alert(myArray[count]);
}
Array.remove()方法
jQuery的创建者John Resig创建了一个非常方便的Array.remove方法,我总是在项目中使用它。
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
下面是如何使用它的一些示例:
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);
John的网站
最简单的方法可能是
var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];
希望这有帮助。参考:https://lodash.com/docs#compact
delete的行为类似于非真实情况,它只是删除项,但数组长度保持不变:
来自节点终端的示例:
> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]
这里有一个函数,使用slice()按索引删除数组中的项,它将arr作为第一个参数,将要删除的成员的索引作为第二个参数。如您所见,它实际上删除了数组的成员,并将数组长度减少1
function(arr,arrIndex){
return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}
上面的函数所做的是将索引之前的所有成员和索引之后的所有成员连接在一起,并返回结果。
下面是一个使用上述函数作为节点模块的示例,查看终端将非常有用:
> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3
请注意,这不会在一个数组中使用重复数据,因为indexOf(“c”)只会得到第一次出现,并且只会拼接并删除它找到的第一个“c”。