在数组元素上使用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的网站
其他回答
如果您的阵列较小,可以使用过滤器:
myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');
如果您想要迭代一个大数组并选择性地删除元素,那么每次删除都调用splice()将非常昂贵,因为splice(()每次都必须重新索引后续元素。因为数组在Javascript中是关联的,所以删除单个元素然后重新索引数组会更有效。
您可以通过构建一个新阵列来实现这一点。例如
function reindexArray( array )
{
var result = [];
for( var key in array )
result.push( array[key] );
return result;
};
但我认为您不能修改原始数组中的键值,这会更有效——看起来您可能需要创建一个新数组。
请注意,您不需要检查“未定义”条目,因为它们实际上并不存在,for循环也不会返回它们。这是数组打印的产物,将它们显示为未定义。它们似乎不存在于记忆中。
如果您可以使用slice()之类的方法,这会很好,因为它会更快,但不会重新索引。有人知道更好的方法吗?
实际上,您可能可以按以下方式就地执行,这可能更高效、更具性能:
reindexArray : function( array )
{
var index = 0; // The index where the element should be
for( var key in array ) // Iterate the array
{
if( parseInt( key ) !== index ) // If the element is out of sequence
{
array[index] = array[key]; // Move it to the correct, earlier position in the array
++index; // Update the index
}
}
array.splice( index ); // Remove any remaining elements (These will be duplicates of earlier items)
},
我有两种方法。
简单的一个:
arr = arr.splice(index,1)
第二个:
arr = arr.filter((v,i)=>i!==index)
第二种方法的优点是可以删除一个值(所有值,而不是像大多数情况一样只删除第一个实例)
arr = arr.filter((v,i)=>v!==value)
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];
如果要删除的元素位于中间(例如,我们要删除索引为1的“c”),可以使用:
var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))