javascript - javascript中排序与if else if选择哪一个?

标签 javascript arrays sorting if-statement

我有一个场景,我需要按照索引号的升序显示数据。

myArray = [
{custom_carousel: false, default_label: "SmartCards", index: 3, visible: true}, 
{custom_carousel: false, default_label: "Pathways", index: 2, visible: false},
{custom_carousel: false, default_label: "Pathways", index: 1, visible: false},
{custom_carousel: false, default_label: "Pathways", index: 0, visible: false}
]

我应该先对数组进行排序还是添加 if else if 条件?

if(index === 0){

}else if (index === 1){

}else if (index === 2){

}else if (index === 3){

}

最佳答案

您可以使用基于index值的sort方法:

myArray = [
{custom_carousel: false, default_label: "Pathways", index: 2, visible: false},
{custom_carousel: false, default_label: "SmartCards", index: 3, visible: true}, 
{custom_carousel: false, default_label: "Pathways", index: 1, visible: false},
{custom_carousel: false, default_label: "Pathways", index: 0, visible: false}
]
console.log(myArray.sort((a,b)=>a.index - b.index));

关于javascript - javascript中排序与if else if选择哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54460790/

相关文章:

javascript - 无法使用 'in' 运算符在 null 中搜索 'selectedItem'

javascript - 使用 JQuery 从输入数字中获取值并更改 css

java - 什么是NumberFormatException,我该如何解决?

Java - 每次调用 int size 方法时,该方法的值都会增加 1

java - 查找有序数组中缺失的整数

javascript - 从缓冲区创建新对象

php - 重新排序订单以提高仓库效率

javascript - 按两个标准对多维数组进行排序?

sorting - hadoop 分区程序不工作

javascript - css 中 java window.pack() 的等价物