在数组元素上使用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);
如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?
当前回答
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
其他回答
可能还值得一提的是,拼接仅适用于阵列。(不能依赖对象财产来遵循一致的顺序。)
要从对象中删除键值对,实际上需要删除:
delete myObj.propName; // , or:
delete myObj["propName"]; // Equivalent.
delete将删除对象属性,但不会重新索引数组或更新其长度。这使得它看起来像是未定义的:
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
请注意,它实际上没有设置为值undefined,而是从数组中删除了属性,使其看起来未定义。Chrome开发工具在记录阵列时打印为空,从而明确了这一区别。
> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
splice(start,deleteCount)实际上删除了元素,重新索引数组,并更改其长度。
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
目前有两种方法可以做到这一点
使用夹板()arrayObject.spling(索引,1);使用deletedelete arrayObject[index];
但我始终建议对数组对象使用拼接,对对象属性使用删除,因为删除不会更新数组长度。
如果您想要迭代一个大数组并选择性地删除元素,那么每次删除都调用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)
},
因为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]);
}