在数组元素上使用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将删除对象属性,但不会重新索引或更新其长度。这使它看起来像是未定义:拼接:实际删除元素,重新索引数组,并更改其长度。
从最后一个删除元素
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];
其他回答
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可以用于其他类型的索引。。
例子:
delete myArray['text1'];
因为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]);
}
function deleteFromArray(array, indexToDelete){
var remain = new Array();
for(var i in array){
if(array[i] == indexToDelete){
continue;
}
remain.push(array[i]);
}
return remain;
}
myArray = ['a', 'b', 'c', 'd'];
deleteFromArray(myArray , 0);
//结果:myArray=['b','c','d'];
应用delete运算符和splice()方法后,通过记录每个数组的长度可以看出差异。例如:
删除运算符
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5
delete运算符从数组中删除元素,但元素的“占位符”仍然存在。橡树已经被移除,但它仍然占用阵列中的空间。因此,阵列的长度保持为5。
拼接()法
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4
splice()方法完全删除目标值和“占位符”。橡树已经被移除,以及它在阵列中占据的空间。阵列的长度现在为4。