在数组元素上使用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);
如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?
当前回答
拼接将使用数字索引。
而delete可以用于其他类型的索引。。
例子:
delete myArray['text1'];
其他回答
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”。
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的网站
删除Vs接头
从数组中删除项时
var arr=[1,2,3,4];删除arr[2]//结果[1,2,3:,4]控制台日志(arr)
当您拼接时
var arr=[1,2,3,4];arr.splice(1,1)//结果[1,3,4]控制台日志(arr);
如果删除,元素将被删除,但索引仍为空
而在拼接元件被删除的情况下,其余元件的索引相应地减少
其他人已经正确比较了删除和拼接。
另一个有趣的比较是delete与undefined:一个被删除的数组项比一个刚刚设置为undefineed的数组项使用更少的内存;
例如,此代码不会完成:
let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
ary.push(y);
ary[y] = undefined;
y += 1;
}
console(ary.length);
它会产生以下错误:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
所以,正如您所看到的,undefined实际上占用了堆内存。
但是,如果您还删除了ary项(而不是将其设置为undefined),代码将缓慢完成:
let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
ary.push(x);
ary[x] = undefined;
delete ary[x];
x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);
这些都是极端的例子,但它们表明了我在任何地方都没有看到有人提到的删除。
function remove_array_value(array, value) {
var index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
reindex_array(array);
}
}
function reindex_array(array) {
var result = [];
for (var key in array) {
result.push(array[key]);
}
return result;
}
例子:
var example_arr = ['apple', 'banana', 'lemon']; // length = 3
remove_array_value(example_arr, 'banana');
香蕉被删除,数组长度=2