试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)
我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。
有没有办法让排序函数对整数值进行排序?
试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。
var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)
我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。
有没有办法让排序函数对整数值进行排序?
当前回答
对整数> 0排序,跳出框框思考:
函数sortArray(arr) { return new Promise((resolve) => { Const result = [] arr.forEach((item) => { setTimeout(() => { result.push(项) 如果结果。长度== arrr . Length) resolve(result) },项) }) }) } sortArray([4,2, 42岁,128年,56岁的2]),然后((结果)= > { document . write (JSON.stringify(结果)) })
请注意,这不应该有效地使用,.sort()更适合于此,检查其他答案
其他回答
数组中。Sort默认执行字典排序,对于数字排序,提供自己的函数。这里有一个简单的例子:
function compareNumbers(a, b)
{
return a - b;
}
numArray.sort(compareNumbers);
还要注意,排序是“就地”工作的,不需要赋值。
排序函数的行为如此怪异的原因
从文档中可以看到:
[…数组根据每个字符的Unicode码位排序 值,根据字符串转换每个元素。
如果你打印数组的unicode点值,那么它就会被清除。
console.log(“140000”.charCodeAt (0)); console.log(“104”.charCodeAt (0)); console.log(“99”.charCodeAt (0)); //请注意,我们只查看数字charCodeAt(0)的第一个索引
返回:“49,49,57”。
49 (unicode value of first number at 140000)
49 (unicode value of first number at 104)
57 (unicode value of first number at 99)
现在,因为140000和104返回了相同的值(49),它切断了第一个索引并再次检查:
console.log(“40000”.charCodeAt (0)); console.log(“04”.charCodeAt (0)); //请注意,我们只查看数字charCodeAt(0)的第一个索引
52 (unicode value of first number at 40000)
40 (unicode value of first number at 04)
如果我们对这个进行排序,那么我们会得到:
40 (unicode value of first number at 04)
52 (unicode value of first number at 40000)
所以104在140000之前。
所以最终的结果是: var numArray = [140000, 104,99]; numArray = numArray.sort(); console.log (numArray)
104, 140,000, 99
结论:
Sort()仅通过查看数字的第一个索引来排序。Sort()并不关心一个整数是否比另一个大,它比较数字的unicode值,如果有两个相同的unicode值,那么它检查是否有下一个数字并进行比较。
要正确排序,必须向sort()传递一个比较函数,就像这里解释的那样。
虽然在JavaScript中不是必需的,但如果希望sort() compareFunction严格返回-1、0或1(类似于PHP中的宇宙飞船操作符的工作方式),则可以使用Math.sign()。
下面的compareFunction严格返回-1、0或1:
numArray.sort((a, b) => Math.sign(a - b));
注意:Internet Explorer不支持Math.sign()。
sort_mixed
Object.defineProperty(Array.prototype,"sort_mixed",{
value: function () { // do not use arrow function
var N = [], L = [];
this.forEach(e => {
Number.isFinite(e) ? N.push(e) : L.push(e);
});
N.sort((a, b) => a - b);
L.sort();
[...N, ...L].forEach((v, i) => this[i] = v);
return this;
})
try a =[1,'u',"V",10,4,"c"," a "].sort_mixed();console.log (a)
你可以简单地排序数字数组
常量数字=[13,17,14,19,16]; 让温度; for(let i=0;i<num.length;i++){ for(let j=i+1;j<num.length;j++){ if(num[i]>num[j]){ 温度=数字[i] 数字[i]=数字[j] 数字[j]=温度 } } } 控制台.log(数字);