Home > Net >  Change two-dimentional array's certain index value javascript
Change two-dimentional array's certain index value javascript

Time:12-17

I'm trying to put certain value in certain two dimentional array but it appends different.

Here is my code.

const arr = []
const tdArr = []

arr.length = 5
arr.fill('p', 0)

for(let i = 0; i < arr.length; i  ){
  tdArr.push(arr)
}

const makeRnd = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min))   min
}

let firstRnd = makeRnd(0, 4)
let secRnd = makeRnd(0, 4)
let tdArr2 = [...tdArr]
tdArr2[firstRnd][secRnd] = 'q'

console.log(tdArr2)

I don't know why not (for example) tdArr2[0][1] is not changed but also change all second value of arrays. It seems easy one but cannot google it :( Thanks for help!

CodePudding user response:

Use tdArr.push([...arr]) in the for loop instead of tdArr.push(arr).

const arr = []
const tdArr = []

arr.length = 5
arr.fill('p', 0)

for(let i = 0; i < arr.length; i  ){
  tdArr.push([...arr])
}

const makeRnd = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min))   min
}

let firstRnd = makeRnd(0, 4)
let secRnd = makeRnd(0, 4)
let tdArr2 = [...tdArr]
tdArr2[firstRnd][secRnd] = 'q'

console.log(tdArr2)

CodePudding user response:

As mentioned by @Dave Newton every element of tdArr array is the same one which is a reference to arr so when you change a value of arr all elements of tdArr are changes as they all reference the same array.

I would push an array literal instead of creating an array and then push it or create a copy like mentioned in the answer above and push the copy on each iteration.

tdArr.push(['p']);
  • Related