如下面的代码所示,我有一个数组,并且将对象推入循环中。我想做的是根据延迟的值对它进行排序 属性。我使用了以下代码:
delayOfFeatures.sort((a, b) => a.delay - b.delay);
但数组不会改变
代码:
delayOfFeatures.push({ progSpace: progSpace, feature: feature, delay: delay });
答案 0 :(得分:0)
这是一个示例,您可以在其中根据features
属性按升序或降序对delay
数组进行排序。
class Feature {
constructor(name, delay) {
this._name = name;
this._delay = delay;
}
get name() {
return this._name;
}
get delay() {
return this._delay;
}
}
const features = [
new Feature('Feature A', 1000),
new Feature('Feature C', 500),
new Feature('Feature B', 50),
new Feature('Feature D', 1),
new Feature('Feature E', 750),
];
// Ascending by delay
features.sort((a, b) => a.delay - b.delay);
console.log(features);
// Descending by delay
features.sort((a, b) => b.delay - a.delay);
console.log(features);