gpt4 book ai didi

javascript - 具有空值的 localeCompare 数组

转载 作者:数据小太阳 更新时间:2023-10-29 05:54:24 25 4
gpt4 key购买 nike

当我对我的数组进行排序时,我在控制台中收到以下错误:

Uncaught TypeError: Cannot read property 'localeCompare' of null

到目前为止我尝试了什么:

HTML:

<table class="table table table-striped table-bordered table-hover" id="userLastSyncTable">
<thead>
<tr>
<th class="sortable sortDevicePlatform orderDevicePlatformByASC">Device Platform</th>
</tr>
</thead>
<tbody></tbody>

JavaScript/JQuery:

var TestArray = ["iOS 7", null, "iOS 8.4", null, null, null, "iOS 9"];

ShowUserSyncTable();

function ShowUserSyncTable() {
var tableRecord = '';

// Loop through all the returned records and add them to select box
for (var i = 0; i < TestArray.length; i++) {
tableRecord += "<tr id=" + "" + "><td>" + TestArray[i] + "</td></tr>";

}

$('#userLastSyncTable').find('tbody').html(tableRecord);
}

$(".sortDevicePlatform").click(function () {

var clickedDevicePlatformSorting = $(this).hasClass('orderDevicePlatformByASC') ? 'orderDevicePlatformByDESC' : 'orderDevicePlatformByASC';

$('.sortDevicePlatform').removeClass('orderDevicePlatformByASC').removeClass('orderDevicePlatformByDESC');
$('.sortDevicePlatform').addClass(clickedDevicePlatformSorting);
// Sort the sync list based on device platform
TestArray.sort(function (a, b) {

if (!a) {
// Change this values if you want to put `null` values at the end of the array
return -1;
}
if (!b) {
// Change this values if you want to put `null` values at the end of the array
return +1;
}

if (clickedDevicePlatformSorting == 'orderDevicePlatformByASC' && a) return a && b ? a.localeCompare(b) : -1;
else if (b) return a && b ? b.localeCompare(a) : 1;
});

ShowUserSyncTable();
});

如何使用空值对数组进行排序?

更新 Fiddle 以进行测试:

FIDDLE

预期结果:

一键显示:

iOS 7、iOS 8.4、iOS 9,空,空,空,空

另一种点击显示:

iOS 9、iOS 8.4、iOS 7,空,空,空,空

最佳答案

您不能在 null 上调用函数。您的数组中有一些 null 值。因此,当您尝试对这些值进行排序时,它会崩溃。

您可以保护您的代码以避免这种情况。

TestArray.sort(function(a, b) {
if (!a) {
// Change this values if you want to put `null` values at the end of the array
return -1;
}

if (!b) {
// Change this values if you want to put `null` values at the end of the array
return +1;
}

if (sorted)
return a.localeCompare(b);
else
return b.localeCompare(a);
});

但在我看来,您应该去掉数组中的这个null 值。您可以过滤它们:

TestArray = TestArray.filter(function(val) {
return val != null;
});

关于javascript - 具有空值的 localeCompare 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32946803/

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