在一個有用的示例中,如何使用多個屬性對一個物件陣列進行排序,執行排序的代碼使用一個while回圈(見下面代碼片段中的students1)。 我試圖通過使用.forEach來簡化while回圈,但得到了一個不同的結果集(見students2)。 在使用.forEach的重構中,哪里出了問題,以至于它沒有得到與while回圈相同的輸出?
const students = [
{
firstName: 'John',
lastName: 'Appletree',
等級: 12.
},
{
firstName: 'Mighty',
lastName: 'Peachtree',
grade: 10。
},
{
firstName: 'Kim',
lastName: 'Appletree',
等級: 11。
},
{
firstName: 'Shooter',
lastName: 'Appletree',
等級: 12.
},
{
firstName: 'Peter',
lastName: 'Peachtree',
grade: 12
}
];
const sortBy = [
{
prop:'grade' ,
direction: -1prop: 'lastName',
direction: 1, direction.
}
];
const students1 = JSON. parse(JSON.stringify(students))。
const students2 = JSON. parse(JSON.stringify(students))。
students1.sort((a, b) =>/span> {
let i = 0, result = 0;
while (i < sortBy.length && result ==0) {
const prop = sortBy[i].prop;
const direction = sortBy[i].direction;
結果 = 方向 *
(
a[prop].toString() < b[prop].toString() ? -1 :
(a[prop].toString() > b[prop].toString() ? 1 : 0)
);
i ;
}
return result;
});
students2.sort((a, b) => {
let result = 0;
sortBy.forEach(o => {
result = o.direction *
(
a[o.prop].toString() < b[o.prop].toString() ? -1 :
(a[o.prop].toString() > b[o.prop].toString() ? 1 : 0)
);
});
return result;
});
console.log(學生)。
console.log('one'/span>, students1)。
console.log('two', students2);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你的forEach和while回圈并不真正等同。如果while條件只是i < sortBy.length,那么它就可以作業。在這里,你有一個額外的條件result ===0,而forEach并沒有考慮到這一點。
uj5u.com熱心網友回復:
你沒有完全實作while回圈中的條件:
const students = [
{
firstName: 'John',
lastName: 'Appletree',
等級: 12.
},
{
firstName: 'Mighty',
lastName: 'Peachtree',
grade: 10。
},
{
firstName: 'Kim',
lastName: 'Appletree',
等級: 11。
},
{
firstName: 'Shooter',
lastName: 'Appletree',
等級: 12.
},
{
firstName: 'Peter',
lastName: 'Peachtree',
grade: 12
}
];
const sortBy = [
{
prop:'grade' ,
direction: -1prop: 'lastName',
direction: 1, direction.
}
];
const students1 = JSON. parse(JSON.stringify(students))。
const students2 = JSON. parse(JSON.stringify(students))。
students1.sort((a, b) =>/span> {
let i = 0, result = 0;
while (i < sortBy.length && result ==0) {
const prop = sortBy[i].prop;
const direction = sortBy[i].direction;
結果 = 方向 *
(
a[prop].toString() < b[prop].toString() ? -1 :
(a[prop].toString() > b[prop].toString() ? 1 : 0)
);
i ;
}
return result;
});
students2.sort((a, b) => {
let result = 0;
sortBy.forEach(o => {
if (result !== 0) return;
結果 = o.direction *
(
a[o.prop].toString() < b[o.prop].toString() ? -1 :
(a[o.prop].toString() > b[o.prop].toString() ? 1 : 0)
);
});
return result;
});
console.log(學生)。
console.log('one'/span>, students1)。
console.log('two', students2);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/327345.html
標籤:
