![](/img/trans.png)
[英]I have created a new Array by Object constructor, why it's nature is still array
[英]Why can't I access the [0][0] position of my 2 dimensional array created with 'new Array' constructor?
我需要創建一個接收高度和寬度並創建二維數組的 function。 我的 function 似乎正在實現這一點,但是當我嘗試更改已創建數組的 position [0][0] 時,它會更改我內部 arrays 的所有第一個位置(為了更清晰,請參閱片段)。
我究竟做錯了什么?
function createArr(height, width) { return new Array(height).fill(new Array(width).fill(1)); } const myArr = createArr(3,2) console.log(myArr) //Expected output: [[1,1],[1,1],[1,1]] myArr[0][0] = 5; console.log(myArr) // Expected output: [[5,1],[1,1],[1,1]] // Real output: [[5,1],[5,1],[5,1]]
問題是使用new Array(width).fill(1)
創建的相同數組引用正在為所有高度傳遞。 因此,如果您更改任何數組,似乎所有 arrays 都發生了變化,但實際上它的引用是為所有height
傳遞的同一個數組。 因此,對於每個height
,您需要使用new Array()
構造函數為每個height
創建單獨的 arrays
function createArr(height, width) {
const arr = [];
for(let i=0; i<height; i++){
// You need to create new array for every height
arr[i] = new Array(width).fill(1);
}
return arr;
}
const myArr = createArr(3,2)
console.log(myArr)
//Expected output: [[1,1],[1,1],[1,1]]
myArr[0][0] = 5;
console.log(myArr)
// Actual output: [[5,1],[1,1],[1,1]]
const val = 1; function createdArr(R,C) { var arr = Array(R); for (var i = 0; i < R; i++) { arr[i] = Array(C).fill(val); } return arr; } var ary = createdArr(3,2); console.log(ary); ary[0][0]=5; console.log(ary);
更新:發布有點晚了,@Rishabh 已經有理由回答了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.