为什么排序显示不同的行为进行分类处理并多头排列,短阵?

问题描述 投票:-3回答:2

我有两个arrays objects其中一个具有两个属性same(0)for allvalue(0,1,2,...)。我创建了使用循环两个阵列。我排序上same的基地阵列。该long变化,但short不 我只是想知道为什么这一切会发生 为什么连改变long阵列

let short = [];
for(let i = 0;i < 5;i++){
  short.push({same:0,value:i});
}
let long = []
for(let i = 0;i < 16;i++){
  long.push({same:0,value:i});
}
//It returns same array with same order
console.log(short.sort((obj1,obj2) => obj1.same - obj2.same));
//It returns array with different order
console.log(long.sort((obj1,obj2) => obj1.same - obj2.same));
javascript arrays sorting
2个回答
2
投票

https://v8.dev/blog/array-sort

此行为取决于实现。如果排序实现stable并具有不可预知的行为,否则你的排序算法,节省了订单。一些发动机使用不同阵列长度不同的算法。有时不稳定可能只在某些长度的阵列中可以看出。

例如,Node.js加载10 V8 6.8 WIL输出:

[ { same: 0, value: 0 },
  { same: 0, value: 1 },
  { same: 0, value: 2 },
  { same: 0, value: 3 },
  { same: 0, value: 4 } ]
[ { same: 0, value: 8 },
  { same: 0, value: 0 },
  { same: 0, value: 2 },
  { same: 0, value: 3 },
  { same: 0, value: 4 },
  { same: 0, value: 5 },
  { same: 0, value: 6 },
  { same: 0, value: 7 },
  { same: 0, value: 1 },
  { same: 0, value: 9 },
  { same: 0, value: 10 },
  { same: 0, value: 11 },
  { same: 0, value: 12 },
  { same: 0, value: 13 },
  { same: 0, value: 14 },
  { same: 0, value: 15 } ]

虽然Node.js的11 V8 7.0稳定排序WIL输出:

[ { same: 0, value: 0 },
  { same: 0, value: 1 },
  { same: 0, value: 2 },
  { same: 0, value: 3 },
  { same: 0, value: 4 } ]
[ { same: 0, value: 0 },
  { same: 0, value: 1 },
  { same: 0, value: 2 },
  { same: 0, value: 3 },
  { same: 0, value: 4 },
  { same: 0, value: 5 },
  { same: 0, value: 6 },
  { same: 0, value: 7 },
  { same: 0, value: 8 },
  { same: 0, value: 9 },
  { same: 0, value: 10 },
  { same: 0, value: 11 },
  { same: 0, value: 12 },
  { same: 0, value: 13 },
  { same: 0, value: 14 },
  { same: 0, value: 15 } ]

0
投票

所述Array.sort比较功能需要两个参数;第1个参数是一个项目,第二个是其他项目。

在你的OP你传递只有1个参数;

下面是它应该是什么样子:

let short = []
let long = []

for(let i = 0; i < 5; i++) {
  short.push({same:0, value: i})
}

for(let i = 0; i < 16; i++){
  long.push({same:0, value: i})
}

console.log('short')
console.log(short.sort((a, b) => a.value - b.value))

console.log('long')
console.log(long.sort((a, b) => a.value - b.value))
© www.soinside.com 2019 - 2024. All rights reserved.