我正试图通过使用当前数组长度作为下一个索引来向数组添加项。例如:
var arr = ["one","two","three"];
arr[this.length] = "four";
但它只是用新的元素替换第一个元素,所以我得到CCD_ 1。this
不是指数组吗?
您实际使用的是Window
对象中的属性length
。
窗口长度
返回窗口中的帧数(或元素数(。
在您的情况下,返回0
console.log("length" in window);
console.log(window.length);
你真正想做的是
var arr = ["one","two","three"];
arr[arr.length] = "four";
console.log(arr);
this
是否未引用数组?
不,它没有。要理解this
的含义,请阅读https://www.w3schools.com/js/js_this.asp.在这里的代码中,您需要使用arr.length
。或者,可以使用arr.push()
将元素附加到数组的末尾。
使用ES6析构函数语法,没有副作用。。。
const arr = ['one', 'two', 'three'];
const withFour = [...arr, 'four'];
为什么不简单地使用["four", "two", "three"]
0方法呢?
var arr = ["one","two","three"];
arr.push("four");
更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push