我正在尝试学习打字稿,我想了解为什么我在这里提供的这段代码中https://codepen.io/anon/pen/EpVMJX。尽管我将结果分配给res变量,但测试数组在对其排序后更改了顺序。我假设是因为排序会自动更改排序后的数组。但是我也尝试在排序之前将原始数组复制到另一个变量(defaultArr),并且它也改变了顺序。
let arr:any = [
{ count: 13, year: '1956' },
{ count: 1, year: '1971' },
{ count: 23, year: '1989' },
{ count: 11, year: '1988' }];
let defaultArr = arr;
async function foo(){
console.log(defaultArr);
console.log(arr);
let res = arr.sort((n1,n2)=> n1.count > n2.count? -1:1);
console.log(res);
}
foo();
如何使其表现得像原始数组不会改变其顺序?
答案 0 :(得分:1)
我认为是因为排序会自动更改排序后的数组。
正确,sort
更改您调用它的数组。返回值只是对同一数组的引用(为方便起见)。
但是我也尝试在排序之前将原始数组复制到另一个变量(defaultArr),并且它也改变了顺序。
您没有复制数组,只是将 reference 复制到了数组。您最终以arr
和defaultArr
指向相同数组对象:
arr[Ref:55461]−−−−−−−−−−−−+ | +−−−−−−−−−+ +−−>| (array) | | +−−−−−−−−−+ defaultArr[Ref:55461]−−−−−+
要复制 array ,可以使用slice
:
defaultArr = arr.slice();
其他一些注意事项:
foo
没有理由async
,它没有做任何异步工作。sort
回调不正确,它无法处理计数相等的情况。以下是您的示例,已更新为复制数组,使foo
不是async
,并更正sort
回调(有关详细信息,请参见内联注释):
let arr = [
{ count: 13, year: '1956' },
{ count: 1, year: '1971' },
{ count: 23, year: '1989' },
{ count: 11, year: '1988' }];
// No reason for this to be `async`
function foo(){
let res = arr.slice();
// The `sort` return value should be less than zero if n1 should come before n2,
// greater than zer if n1 should come after n2,
// or zero if they're equivalent for sorting purposes.
// n2.count - n1.count gives us exactly that number, so we can use that directly
res.sort((n1,n2) => n2.count - n1.count);
console.log(res);
}
foo();
.as-console-wrapper {
max-height: 100% !important;
}