我的问题是,如果在 javascript 中,我创建一个数组 a = [2, 3, 4, 5]
并键入 a[5] = 10
然后 a.push(5)
那么编译器是将 5 添加到数组的末尾还是添加到第一个未定义的位置?
我发现它添加到 array 的末尾,即 a[6] == 5
。但我的问题是编译器如何发现数组是否已结束?当然,如果它识别出一个未识别的值,它不能确定一个数组已经结束,因为那样的话数组会在值 5 之后结束。那么,它如何知道数组已经结束?
最佳答案
来自 MDN 的摘要 Array.prototype.push()
:
The
push()
method adds one or more elements to the end of an array and returns the new length of the array.
它知道结尾在哪里,因为数组的长度
总是numerically greater than the highest index in the array .
var a = [1, 2, 3];
a[49] = 4;
document.write(a.join(" - "));
document.write("<br>");
document.write("Array length: " + a.length);
document.write("<br>");
a.push(5);
document.write("<br>");
document.write(a.join(" - "));
document.write("<br>");
document.write("Array length: " + a.length);
关于javascript - a.push() 在数组中增加什么值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34356059/