为什么即使未使用数组排序方法分配数组也要反转?

时间:2018-08-09 12:07:00

标签: javascript

鉴于以下情况:

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 个答案:

答案 0 :(得分:2)

Array.prototype.sort修改原始数组。您需要将ary克隆到ary2中,然后对ary2进行排序。