代码之家  ›  专栏  ›  技术社区  ›  dmgig

Javascript:for循环期间构建的数组的顺序重置[重复]

  •  3
  • dmgig  · 技术社区  · 7 年前

    let arr = [1,2,3,4,5,6]
    let store = [];
    
    for(i = 0; i < arr.length; i++){
      console.log(arr)
      store.push(arr)
      arr.push(arr.shift())
    }
    console.log('store', JSON.stringify(store))
    

    我期待它回来

    [[1,2,3,4,5,6],[2,3,4,5,6,1],[3,4,5,6,1,2],[4,5,6,1,2,3],[5,6,1,2,3,4],[6,1,2,3,4,5]]
    

    [[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]]
    

    在控制台中打印值时,它们看起来是正确的,但在记录store变量时,它们都被重新排序。

    [1, 2, 3, 4, 5, 6]
    [2, 3, 4, 5, 6, 1]
    [3, 4, 5, 6, 1, 2]
    [4, 5, 6, 1, 2, 3]
    [5, 6, 1, 2, 3, 4]
    [6, 1, 2, 3, 4, 5]
    

    为什么会发生这种情况?

    这里有一个类似的问题,但它并没有真正为我的案例提供答案。

    Creating a pair of arrays from an array resulting in circular array

    5 回复  |  直到 7 年前
        1
  •  3
  •   Akrion    7 年前

    只需确保您正在插入 不

    let arr = [1,2,3,4,5,6]
    let store = [];
    
    for(i = 0; i < arr.length; i++){
      store.push(Array.from(arr))  // <-- Make sure not the same ref
      arr.push(arr.shift())
    }
    console.log('store', JSON.stringify(store))
        2
  •  1
  •   George Helyar    7 年前

    store 包含的实例相同 arr 商店

    要获得所需的行为,您需要每次添加一个新实例,例如,在添加实例时对其进行克隆。

        3
  •  1
  •   Nina Scholz    7 年前

    您可以推送不保留相同对象引用的副本。

    let arr = [1, 2, 3, 4, 5, 6]
    let store = [];
    
    for (i = 0; i < arr.length; i++) {
      store.push(arr.slice())                // just take a copy
      arr.push(arr.shift())
    }
    console.log(store.map(a => a.join(' ')))
        4
  •  1
  •   charlietfl    7 年前

    另一种方法是保持原始数组不变并使用 splice() concat() 加

    let arr = [1,2,3,4,5,6];
    
    let store = arr.map((_,i)=> {
       let a = arr.slice();
       return i ? a.concat(a.splice(0,i)) : a;
    })
    
    console.log(JSON.stringify(store))
        5
  •  1
  •   Ank    7 年前

    例子:

    最后:
    arr-参考0x112-值=[1,2,3,4,5,6]

    存储[]=[ref(0x112)、ref(0x112)、ref(0x112)、ref(0x112)、ref(0x112)、ref(0x112)、ref(0x112)]

    let arr = [1,2,3,4,5,6]
    let store = [];
    
    for(i = 0; i < arr.length; i++){
      console.log(arr)
      let newArr = arr.slice();
      store.push(newArr)  
      arr.push(arr.shift())
    }
    console.log('store', JSON.stringify(store))