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' 中的数组?
解决方案
Array.prototype.sort
修改原始数组。您需要克隆ary
到ary2
然后排序ary2
。
推荐阅读
- python - 在 python 中复制列表时使用 list() 的复杂性是什么?
- java - Docusign SDK for Java 可用于非 Web 应用程序
- promela - 我如何在 spin 中定义这样的宏?
- jquery - 每次按下按钮如何产生随机选项?
- sql - 选择雪花中字符串左侧的第一个单词
- vb.net - 如何将程序拆分为几个逻辑部分?
- javascript - 使用 querSelectorAll 获取所有子元素并添加到它们的 ClassList 时出现问题
- javascript - JsDocs:您如何记录工厂函数中的方法?
- python - 如何将文本文件转换为分隔的列表列表
- excel - Excel VBA 读取 XML 错误(空白属性?)