数组列表元素上的JavaScript删除运算符 [英] Javascript delete operator on array list element
问题描述
我对在数组元素上使用删除运算符感到困惑。
I am confused about delete operator use on array element.
我发现delete可以与数组元素一起使用,并且删除了元素但不更新数组length,所以基本上该元素被undefined代替。但是当我测试它时,我发现它被替换为空白。
I found that delete can be used with array elements and it removes the element but doesn't update array length , so basically that element is replaced with undefined.But when i tested it I found that it replaces it with blank.
var test = new Array()
delete test[id];
所以我对此有3分
-
test [id]
中的id是元素或元素的索引,因为我读到id可以是两者。但是,当我测试它时,我发现它只有在通过索引时才起作用。
test[id]
id in this is element or index of element, as I read that id can be both. But when I tested it , I found its working only when i pass index.
如果数组没有任何元素并且我尝试通过传递任何值来删除该怎么办像 delete test [3]
?
What if the array has no element and I try to delete by passing any value like delete test[3]
?
推荐答案
Don't use delete
on array, use splice()
-
删除
实际上不会从数组中删除该元素。只需将值设置为undefined
-
delete
不变长度
数组
delete
will not remove the element actually from array. It'll just set the value toundefined
delete
does not alter thelength
of array
删除
演示
delete
Demo
var arr = [1, 2, 3, 4, 5];
delete arr[2];
document.write(arr);
console.log(arr);
document.write('<br />Length: ' + arr.length);
使用 splice()
splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
如果传递了超出范围的索引以删除,则 splice()
将静默返回。
splice()
will return silently, if you passed an out of bound index to remove.
arr.splice(indexToDelete, 1);
splice()
演示
splice()
Demo
var arr = [1, 2, 3, 4, 5];
arr.splice(2, 1);
arr.splice(100, 1); // For out of bounds index, it fails silently
document.write(arr);
console.log(arr);
document.write('<br />Length: ' + arr.length);
这篇关于数组列表元素上的JavaScript删除运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!