gpt4 book ai didi

javascript - 多次 array.sort 后数组顺序发生变化

转载 作者:行者123 更新时间:2023-11-28 14:41:41 27 4
gpt4 key购买 nike

我有一个对数组进行排序的代码

const timeSorted = wheater.list.sort((z,x)=>
{
return z.dt- x.dt
})
console.log(timeSorted)

我得到的输出已排序
但如果我添加另一种这样的排序

const timeSorted = wheater.list.sort((z,x)=>
{
return z.dt- x.dt
})
const tempSorted = wheater.list.sort((a,b)=>
{
return a.main.temp - b.main.temp
})
console.log(timeSorted)

const timeSorted 变为 tempSorted

我该如何解决这个问题?

最佳答案

数组已按原位排序。

为了不更改它,您需要使用 oldArray.slice() 创建先前数组的副本。

const tempSorted = wheater.list.slice().sort((a,b)=>
{
return a.main.temp - b.main.temp
})

关于javascript - 多次 array.sort 后数组顺序发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47868148/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com