【发布时间】:2015-10-05 10:51:09
【问题描述】:
当我对数组进行排序时,控制台中出现以下错误:
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 进行测试:
预期结果:
一键播放:
iOS 7、iOS 8.4、iOS 9、空、空、空、空
再次点击展示:
iOS 9、iOS 8.4、iOS 7、空、空、空、空
【问题讨论】:
-
你希望你的
null值去哪里?上榜还是下榜? -
为什么你甚至想要空值?要删除它们吗?
-
@Chris Beckett。排序后的输出期望是什么。
-
@SheraliTurdiyev 检查我新更新的小提琴,它给你更多的想法
标签: javascript jquery arrays