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

为什么即使没有使用数组排序方法分配数组,数组也会被反转?

  •  0
  • Remi  · 技术社区  · 6 年前

    考虑到以下情况:

    let ary = [1, 2, 3];
    
    console.dir(ary);
    // ^ this console.dir outputs the reversed order, even though ary is not defined using a sort
    // 3, 2, 1
    
    function x(ary) {
      let ary2 = ary.sort( function(a,b) { return b-a } );
      // only define ary2 as the sorted array
      return ary2;  
    }
    
    document.getElementById('locationAry2').innerHTML = x(ary);
    // ^ this is correct since ary2 is reversed in function x
    <p id="locationAry2"></p>

    当只对ary2进行排序时,为什么它返回变量“ary”排序中的数组?

    1 回复  |  直到 6 年前
        1
  •  2
  •   dislick    6 年前

    Array.prototype.sort 修改原始数组。你需要克隆 ary 进入之内 ary2 然后排序 芳基 .