对数组进行排序时,在控制台中出现以下错误:
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();
});
如何使用空值对数组进行排序?
更新小提琴进行测试:
预期结果:
一键显示:
iOS 7,iOS 8.4,iOS 9,null,null,null,null
另一个点击显示:
iOS 9,iOS 8.4,iOS 7,null,null,null,null
试试这个:演示。
orderDevicePlatformByASC
从clickable中删除类名称<th ...>
。因为,它的最初外观未排序。使用它进行排序。
TestArray.sort(function (a, b) {
if (clickedDevicePlatformSorting == 'orderDevicePlatformByASC' && a)
return b ? a.localeCompare(b) : -1;
else if (b)
return a ? b.localeCompare(a) : 1;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句