在数组元素上使用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);
如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?
当前回答
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的网站
其他回答
delete:delete将删除对象属性,但不会重新索引或更新其长度。这使它看起来像是未定义:拼接:实际删除元素,重新索引数组,并更改其长度。
从最后一个删除元素
arrName.pop();
从第一个删除元素
arrName.shift();
从中间删除
arrName.splice(starting index,number of element you wnt to delete);
Ex: arrName.splice(1,1);
从最后一个元素中删除一个元素
arrName.splice(-1);
使用数组索引号删除
delete arrName[1];
保持简单:-
当您删除数组中的任何元素时,它将删除所述位置的值,并使其为空/未定义,但该位置存在于数组中。
var arr=[1,2,3,4,5];函数del(){删除arr[3];控制台日志(arr);}德尔(arr);
其中,与拼接原型一样,参数如下//arr.splice(开始删除的位置,要删除的项目数)
var arr=[1,2,3,4,5];函数spl(){arr.splice(0,2);//arr.splice(开始删除的位置,要删除的项目数)控制台日志(arr);}spl(arr);
拼接将使用数字索引。
而delete可以用于其他类型的索引。。
例子:
delete myArray['text1'];
从核心JavaScript 1.5参考>运算符>特殊运算符>删除运算符:
删除数组元素时数组长度不受影响。对于例如,如果删除[3],则[4]为仍然a[4]和a[3]未定义。这即使删除最后一个数组的元素(删除a[a.length-1])。
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的网站