Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

JavaScript 使用 console.log 方法打印数组后,对数组重新排序,先前打印的结果也排序了?

题目描述

对一个数组进行排序,使用 sort 方法,在执行 sort 方法前后分别使用console.log方法输出该数组,发现 sort 方法前后输出的都是排序之后的数组。

题目来源及自己的思路

题目来自于日常开发,怀疑是js执行顺序的问题。

相关代码

粘贴代码文本(请勿用截图)

const list = [{sort: 1}, {sort: 2}, {sort: 3}];
console.log(list);
list.sort((a, b) =>  b.sort - a.sort);
console.log(list);

你期待的结果是什么?实际看到的错误信息又是什么?

期待的结果是:
第一次输出的是排序前的数组——

[{sort: 1}, {sort: 2}, {sort: 3}]

第二次输出的是排序后的数组——

[{sort: 3}, {sort: 2}, {sort: 1}]


在chrome中看到的实际结果却是:
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...