0

i try to initial my array using this

     // first approach
    createInitial(){
        let result = []
        let temp = []
        console.log(this.grid)
        for(let j=0;j<this.grid;j++){
            temp.push(false)
        }
        for(let i=0;i<this.grid;i++){
            result.push(temp)
        }

when i want to change value ex. result [0][0] = true result will be

result = [[true,false],[true,false]]

Full code https://github.com/son1122/tic-tac-toe

If i use Hard code for initial like this result = [[false,false],[false,false]] the result will be correct as i want result = [[true,false],[false,false]]

i believe that instead to push value it push reference to the same variable and i make it to work now. however i curios why this happen.so i want to ask is

  1. this normal?
  2. and what can i do to make
    result.push(temp) work or i should use different approach. or do we have a way to push value instead of ref
  3. can someone provide more information about this ?

thank you everyone for provide any help.

asd1122
  • 11
  • Does this answer your question? [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Titus Nov 20 '22 at 13:43
  • What is `grid`? – bloodyKnuckles Nov 20 '22 at 13:48
  • @bloodyKnuckles grid is each player array of tic tac toe. in this project i try to make a tic tac toe to beable to change size of grid from 3*3 to n*n and player from 2 player to n player – asd1122 Nov 21 '22 at 05:31
  • @Titus i believe yes and no at the same time https://stackoverflow.com/a/5314911/17475708 from this he state that js is pass by value except object but i didnt use object so i not sure why this happen or how i know what specific data type that pass by reference – asd1122 Nov 21 '22 at 05:32

0 Answers0