我有一个场景,在这个场景中,我需要以索引号的递增顺序显示数据。
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){
}发布于 2019-01-31 20:43:49
您可以使用基于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));
发布于 2019-01-31 20:44:26
myArray.sort(function(a, b){return a.index - b.index});将按索引对数组进行排序
发布于 2019-01-31 20:42:05
我建议提前对数组进行排序,然后按数组的索引进行访问。
的原因
var 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 }]
myArray.sort(({ index: a }, { index: b }) => a - b);
console.log(myArray);
https://stackoverflow.com/questions/54460790
复制相似问题