Я хочу отсортировать таблицу по длине данных. Но есть некоторые нулевые значения. Это моя функция сортировки
sorter: (a, b) => a.rechargeType.length - b.rechargeType.length
Следующая ошибка появляется, когда есть нулевое значение
TypeError: Cannot read property 'length' of null
Вы можете просто сделать это,
sorter: (a, b) => {
if (a && a.rechargeType && a.rechargeType.length && b && b.rechargeType && b.rechargeType.length) {
return a.rechargeType.length - b.rechargeType.length;
} else if (a && a.rechargeType && a.rechargeType.length) {
// That means be has null rechargeType, so a will come first.
return -1;
} else if (b && b.rechargeType && b.rechargeType.length) {
// That means a has null rechargeType so b will come first.
return 1;
}
// Both rechargeType has null value so there will be no order change.
return 0;
}
Таким образом, нулевые значения будут последними. Чтобы узнать больше о возвращаемом значении функции сравнения сортировки, вы можете прочитать это.