Aja*_*ayc 4 javascript arrays sorting
Heyo!
我正在尝试对有时可能完全相同的数组进行排序.当数组不相等时,该函数可以正常工作,但是当它完全相等时,似乎随机放置元素.例如,我希望下面的代码可以打印'a,b,c ......',而是得到类似:'k,a,c,d ......'.这是sort()函数的预期行为吗?如何生成'a,b,c ......'功能?谢谢!
var arrayToSort = [
{name: 'a', strength: 1}, {name: 'b', strength: 1}, {name: 'c', strength: 1}, {name: 'd', strength: 1},
{name: 'e', strength: 1}, {name: 'f', strength: 1}, {name: 'g', strength: 1}, {name: 'h', strength: 1},
{name: 'i', strength: 1}, {name: 'j', strength: 1}, {name: 'k', strength: 1}, {name: 'l', strength: 1},
{name: 'm', strength: 1}, {name: 'n', strength: 1}, {name: 'o', strength: 1}, {name: 'p', strength: 1},
{name: 'q', strength: 1}, {name: 'r', strength: 1}, {name: 's', strength: 1}, {name: 't', strength: 1}
];
arrayToSort.sort(function (a, b) {
return b.strength - a.strength;
});
arrayToSort.forEach(function (element) {
console.log(element.name);
});
Run Code Online (Sandbox Code Playgroud)