function longest(arr) {
return arr.sort( (a,b) => {
return a.length - b.length;
});
}
var res = longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k','l']);
console.log(res); // -> [ 'f', 'a', 'c', 'd', 'e', 'b', 'g', 'h', 'i', 'k', 'l' ]
这个函数的返回值怎么排序这么奇怪?据我了解,它根本不应该更改数组。
我说的对吗?
最佳答案
Array.prototype.sort
不保证稳定。不保证相同的元素将保留其原始顺序。
The
sort()
method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
关于javascript sort函数在不应该的时候进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303475/