gpt4 book ai didi

javascript排序混合字符串和空值的数组

转载 作者:可可西里 更新时间:2023-11-01 02:14:50 26 4
gpt4 key购买 nike

当对由字符串、空值和零混合组成的数组进行排序时,我得到的结果并不像预期的那样正确,空值似乎被排序为“空”字符串。我这样做了(在 FireFox 上测试过):

var arr1 = arr2 = [null, "b", "c", "d", null, "e", 0, "g", null, 0, "h", "i", "l", "m", "n", "o", "p", "ne", "nur", "nimbus"];

document.write("SORTED ARRAY:<br>");
arr1.sort();
arr1.forEach(function(val){document.write(val + "; ")});

结果是:

排序数组:0; 0; b; C; d; e; G; H;一世; l;米;名词;没;雨云;无效的;无效的;无效的;努尔; Ø; ;

您是否知道如何在数组排序期间将空值视为空字符串,以便它们与零一起出现在排序数组中的第一个。

谢谢!

最佳答案

这将通过将所有内容转换为字符串(特别是将 null 转换为空字符串)并允许 JavaScript 的内置字符串比较来完成您想要的工作:

arr2.sort( function(a, b) 
{
/*
We avoid reuse of arguments variables in a sort
comparison function because of a bug in IE <= 8.
See http://www.zachleat.com/web/array-sort/
*/
var va = (a === null) ? "" : "" + a,
vb = (b === null) ? "" : "" + b;

return va > vb ? 1 : ( va === vb ? 0 : -1 );
} );

关于javascript排序混合字符串和空值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2328562/

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