使用[this.length]向元素添加元素到数组

And*_*Kay -1 javascript arrays this

我试图通过使用当前数组长度作为下一个索引将项添加到数组.例如:

var arr = ["one","two","three"];
arr[this.length] = "four";
Run Code Online (Sandbox Code Playgroud)

但它只是用新元素替换了第一个元素,所以我得到了["four", "two", "three"].是this不是指阵列?

Ele*_*Ele 5

你实际使用物业lengthWindow对象.

Window.length

返回窗口中的帧数(元素或元素).

在你的情况下,正在返回0.

console.log("length" in window);
console.log(window.length);
Run Code Online (Sandbox Code Playgroud)

你真正想做的是

var arr = ["one","two","three"];
arr[arr.length] = "four";

console.log(arr);
Run Code Online (Sandbox Code Playgroud)