新手问题。因此,我正在按升序对数字数组进行排序,但我不明白为什么这样做。
const sortYears = arr => {
arr = (a, b) => {return a - b;}
}
const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922];
console.log(years.sort(sortYears()));
什么是a - b
真正实现?不仅仅是返回另一个号码吗?突然如何对这些数字进行排序?
由0产生的数字a - b
或b - a
与0有关的数字的影响:
b === a
-物品彼此之间的顺序不会改变b - a < 0
-移至a
比b
b - a > 0
-移至b
比a
但是,该sortYears
函数返回undefined
,因此未考虑在内。尽管默认排序是升序的。它是通过将项目转换为字符串并将它们作为字符串排序而创建的。提供比较功能将确保将它们按数字排序(请使用默认的比较来注意数字2的位置):
const sortYears = () => (a, b) => a - b;
const years = [1970, 1999, 1951, 1982, 1963, 2011, 2, 2018, 1922];
console.log(years.sort(sortYears())); // with compare function
// [2,1922,1951,1963,1970,1982,1999,2011,2018]
console.log([...years].sort()); // using the default compare
// [1922,1951,1963,1970,1982,1999,2,2011,2018]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句