在如何使用多个属性对对象数组进行排序的有用示例中,执行排序的代码使用了while循环(请参阅下面代码片段中的students1)。我试图通过使用。 foreach简化while循环,但得到一个不同的结果集(见学生s2)。在使用。forEach进行重构时哪里出了问题,它没有给出与while循环相同的输出?
const students = [
{
firstName: 'John',
lastName: 'Appletree',
grade: 12
},
{
firstName: 'Mighty',
lastName: 'Peachtree',
grade: 10
},
{
firstName: 'Kim',
lastName: 'Appletree',
grade: 11
},
{
firstName: 'Shooter',
lastName: 'Appletree',
grade: 12
},
{
firstName: 'Peter',
lastName: 'Peachtree',
grade: 12
}
];
const sortBy = [
{
prop:'grade',
direction: -1
},
{
prop:'lastName',
direction: 1
}
];
const students1 = JSON.parse(JSON.stringify(students));
const students2 = JSON.parse(JSON.stringify(students));
students1.sort((a, b) => {
let i = 0, result = 0;
while (i < sortBy.length && result === 0) {
const prop = sortBy[i].prop;
const direction = sortBy[i].direction;
result = 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(students);
console.log('one', students1);
console.log('two', students2);
# # #你forEach
and 和
while
loop循环并不是等价的。如果while
condition was just i < sortBy.l条件是
i < sortBy.length
then it would work.然后它就会起作用。这里有一个附加条件result === 0
which forEach
doesn't account for.
forEach
doesn'不占。
的条件还没有完全实现while
loop:
const students = [
{
firstName: 'John',
lastName: 'Appletree',
grade: 12
},
{
firstName: 'Mighty',
lastName: 'Peachtree',
grade: 10
},
{
firstName: 'Kim',
lastName: 'Appletree',
grade: 11
},
{
firstName: 'Shooter',
lastName: 'Appletree',
grade: 12
},
{
firstName: 'Peter',
lastName: 'Peachtree',
grade: 12
}
];
const sortBy = [
{
prop:'grade',
direction: -1
},
{
prop:'lastName',
direction: 1
}
];
const students1 = JSON.parse(JSON.stringify(students));
const students2 = JSON.parse(JSON.stringify(students));
students1.sort((a, b) => {
let i = 0, result = 0;
while (i < sortBy.length && result === 0) {
const prop = sortBy[i].prop;
const direction = sortBy[i].direction;
result = 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;
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(students);
console.log('one', students1);
console.log('two', students2);