sort() 方法用于对数组的元素进行排序。
n3=['b','c','a','z','m']
console.log(n3.sort())
很简单的看出结果为[ ‘a’, ‘b’, ‘c’, ‘m’, ‘z’ ]
n4=[1,3,5,7,2,8,0]
console.log(n4.sort())
结果为[ 0, 1, 2, 3,5, 7, 8]
当数组中有负数时
n2 = [-10,-1,-2,-9]
console.log(n2.sort())
结果变为
查询后得知:
如果调用sort方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。
所以更正代码为:
function sortNumber(a, b) {
return a - b
}
n2 = [-10, -1, -2, -9]
n2.sort(sortNumber)
console.log(n2)
结果:
达到预期