简体   繁体   中英

Typescript/Javascript array push pushes to all arrays in 2d array

This should be very basic but do not working. I am trying to push an element on 2d number array on a specific index, but it is inserting element on every index.

 let adj = new Array(4).fill(new Array()) adj[0].push(1) console.log(adj)

The output I am getting:

[[1], [1], [1], [1]] 

But I am expecting:

[[1], [], [], []]

What you're doing with let adj = new Array(4).fill(new Array()) is just setting adj to an array of references to the same array, thus changing one, changes the others.

To fix this do it like this

 let adj = Array.from(Array(4), () => new Array()); adj[0].push(1); console.log(adj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM