javascript sort函数在不应该的时候进行排序

标签 javascript sorting

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/

相关文章:

json - json 列表排序上的 flutter typeerror

java - 使用正则表达式进行 Sqlite 排序

javascript - 在哪里清理数据客户端或服务器端

javascript - 如何使用 formik react js 在 handlesubmit 函数中接收选择值?

javascript - 在 jquery 中声明一个 if 语句来显示日期

java - 对 javaFX 树 TableView 项目进行排序

C 保持运行信号数组排序

c - 使用 mpi 并行排序

javascript - Session 有时返回 Null 有时返回 value

javascript - 具有深层组件层次结构的 Angular 组件输出/事件