在数组元素上使用delete
运算符与使用Array.splice
方法有什么Array.splice
?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果可以像删除对象一样删除数组元素,为什么还要使用splice方法?
#1楼
在尝试了解如何从数组中删除元素的每次出现时,我偶然发现了这个问题。 这里有一个比较的splice
和delete
去除每一个'c'
从items
阵列。
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
#2楼
如果要迭代一个大数组并有选择地删除元素,则每次删除都调用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)
},
#3楼
值得一提的是,拼接仅适用于数组。 (不能依赖对象属性遵循一致的顺序。)
要从对象中删除键值对,删除实际上是您想要的:
delete myObj.propName; // , or:
delete myObj["propName"]; // Equivalent.
#4楼
你可以用这样的东西
var my_array = [1,2,3,4,5,6]; delete my_array[4]; console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); // [1,2,3,4,6]
#5楼
splice
将与数字索引一起使用。
而delete
可以用于其他类型的索引。
例:
delete myArray['text1'];
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3139278