Changing one array element affects other elements

后端 未结 1 1616
孤城傲影
孤城傲影 2020-12-07 06:29

I have a javascript code as below.

相关标签:
1条回答
  • 2020-12-07 06:57

    Can someone tell what is wrong in this code?

    You're using one row array for all your entries in state. fill takes the value you give it and puts that value in the target array repeatedly. The value you're giving it is a reference to the single array you've created, so all of those entries end up referring to the same row, like this:

                                              +−−−−−−−−−+
    row−−−−−−−−−−−−−−−−−−−−−−−+−+−+−+−+−+−+−−>| (array) |
              +−−−−−−−−−+     | | | | | | |   +−−−−−−−−−+
    state−−−−>| (array) |     | | | | | | |   | 0: 0    |
              +−−−−−−−−−+     | | | | | | |   | 1: 0    |
              | 0       |−−−−−+ | | | | | |   | 2: 0    |
              | 1       |−−−−−−−+ | | | | |   | 3: 0    |
              | 2       |−−−−−−−−−+ | | | |   | 4: 0    |
              | 3       |−−−−−−−−−−−+ | | |   | 5: 0    |
              | 4       |−−−−−−−−−−−−−+ | |   | 6: 0    |
              | 5       |−−−−−−−−−−−−−−−+ |   +−−−−−−−−−+
              | 6       |−−−−−−−−−−−−−−−−−+
              +−−−−−−−−−+
    

    You'll need to create a new row array for each slot in state:

    let state = Array.from({length:7}, () => {
      return new Array(7).fill(0);
    });
    state[0][3] = 2;
    console.log(state);
    .as-console-wrapper {
      max-height: 100% !important;
    }

    ...or with only features present in ES5:

    var state = [0,0,0,0,0,0,0].map(function() {
      return [0,0,0,0,0,0,0];
    });
    state[0][3] = 2;
    console.log(state);
    .as-console-wrapper {
      max-height: 100% !important;
    }

    0 讨论(0)
提交回复
热议问题