gpt4 book ai didi

混合数据类型的 Javascript sort() 数组

转载 作者:行者123 更新时间:2023-11-30 08:36:56 26 4
gpt4 key购买 nike

如果我有一个像这样的数组:

["23", "765", "sfasf", "2.3E-3", "2.3cE-3"]

我如何对其进行排序,以便数字(小数、 float 或科学记数法)按升序排列并在非数字字符串(例如“sfasf”或“2.3cE-3”)之后?

示例数组的预期顺序:

["2.3E-3", "23", "765", "2.3cE-3", "sfasf"]

不能转换为数字的字符串的顺序无关紧要,它们必须在最后。

答案的解决方案:

 $scope.cleanAndOrder = function(dbo, fieldName) {
var textareaId = "textarea"+"_"+fieldName ;
var textarea= document.getElementById(textareaId);

//(+b && (+a!=a)) : return true (converted to 1) if b is a number and a isn't
//(a-b) : then compare the numbers if the first comparaison isn't enough
textarea.value = dbo.attributes[fieldName].sort(function(a,b){ return (+b && !+a) || (a-b) }).join("\n");
var lines = textarea.value.split("\n");
textarea.setAttribute('rows', lines.length +2);
}

最佳答案

你可以做到

var arr = arr.sort(function(a,b){ return ((+b==b) && (+a!=a)) || (a-b) })

想法是做两个比较:

  • (+b==b) && (+a!=a) :返回 true(转换为 1)如果 b 是一个数字而 a 不是
  • a-b : 如果第一次比较不够,则比较数字

更深入:+aa 转换为数字。当且仅当 +a 时,它等于(对于 ==,而不是 for ===)a是一个数字(请记住,NaN 不等于 NaN)。

关于混合数据类型的 Javascript sort() 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com