今天在 Leetcode 刷题踩了一个 JS 的小坑,记录一下。
|
|
第一感觉这两个应该会得到相同的结果,然而实际上是不一样的:
|
|
很明显默认的sort()是按字符串比较,根据MDN,
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.
这背后的逻辑是:JS 数组支持所有类型的元素,统一转换成 String 类型进行比较会比较方便。
因此在对 numerical array 进行 sort 时一定要定义自己的 comparing function。