By default, the sort method sorts elements alphabetically.
(默认情况下,sort方法按字母顺序对元素进行排序。)
To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -(要进行数字排序,只需添加一个处理数字排序的新方法(sortNumber,如下所示)-)
function sortNumber(a, b) { return a - b; } var numArray = [140000, 104, 99]; numArray.sort(sortNumber); console.log(numArray);
In ES6, you can simplify this with arrow functions:
(在ES6中,您可以使用箭头功能简化此操作:)
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
Documentation:
(说明文件:)
Mozilla Array.prototype.sort()
recommends this compare function for arrays that don't contain Infinity or NaN.
(Mozilla Array.prototype.sort()
建议此比较功能用于不包含Infinity或NaN的数组。)
(Because Inf - Inf
is NaN, not 0).((因为Inf - Inf
是NaN,而不是0)。)
Also examples of sorting objects by key.
(还有按键对对象进行排序的示例。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…