在许多语言中,标准动态列表(不是固定大小的数组)类型会在删除项目后调整大小:
python :
myList = ['a', 'b', 'c']
del(myList[0])
print(len(myList)) # Prints '2'
C#:
var myList = new List<string> {"a", "b", "c"};
myList.RemoveAt(0);
Console.WriteLine(myList.Count); // Prints '2'
等等。
然而,在 Javascript 中,列表长度保持不变,即使元素计算为 undefined
(this 告诉我它与 array[index] = undefined
):
Javascript:
var myArray = ['a', 'b', 'c']
delete myArray[0]
console.log(myArray.length) // Prints '3'
console.log(myArray) // Prints "[ , 'b', 'c' ]" in node, '[undefined × 1, "b", "c"]' in Chrome
myArray[0] = undefined
console.log(myArray) // Prints "[ undefined, 'b', 'c' ]" on both node and Chrome
myArray.splice(0, 1)
console.log(myArray) // Prints "['b', 'c']"
我的问题是:
- JS 数组
delete
行为是设计使然还是由于担心破坏遗留代码而无法修复的疏忽?
- 替换已删除数组元素的“类未定义”值到底是什么?
您对 delete
的比较至 RemoveAt
这是不正确的。 delete
不做他们做的事;为此,您将使用 splice
:
var myArray = ['a', 'b', 'c']
myArray.splice(0, 1);
console.log(myArray.length) // Prints '2'
delete
删除条目而不对其他条目重新排序,创建一个稀疏数组(一些条目完全缺失的数组)。 delete
不是真正用于数组,它用于从对象中删除属性;但它适用于数组,因为 JavaScript 中的标准(例如,非类型化)数组 aren't really arrays at all *,它们是对某些属性进行特殊处理的对象,例如名称为“数组索引”的对象(defined 作为字符串名称“...其数值 i
在 +0 ≤ i < 2^32-1
范围内” ) 和 length
.
length
如果您执行以下操作,则值会发生变化:
- 使用任何方法添加或删除条目(
splice
、push
等)。
- 通过分配给等于或大于
length
的索引来添加条目.
- 直接分配给
length
:如果你增加length
,你使数组稀疏;如果减少它,则删除该索引或更高索引处的所有条目。例如,如果你有一个数组 ['a', 'b', 'c', 'd', 'e']
并做 theArray.length = 3
, 它不再有索引 3 ( 'd'
) 或 4 ( 'e'
) 的条目。
Is the JS array delete behaviour by design or an oversight that couldn't be fixed for fear of breaking legacy code?
按设计。如上所述,delete
主要是关于从对象中删除属性。
What exactly is the 'undefined-like' value that replaces the deleted array element
没有一个。这是标准数组是对象这一事实的另一个副产品:如果您尝试从对象中读取属性的值,而该对象不具有该属性,则该“获取”操作的结果是值 undefined
。 .并不是对象中有 undefined
的东西-like 值,它是该对象中根本没有具有该名称的属性。此图可能有用:
var o = {}; // A non-array object
console.log(o.noSuchProperty); // undefined
console.log(o["noSuchProperty"]); // undefined
console.log(o[2]); // undefined
var a = []; // An array object
console.log(a.noSuchProperty); // undefined
console.log(a["noSuchProperty"]); // undefined
console.log(a[2]); // undefined
* (这是我贫血的小博客上的帖子)