gpt4 book ai didi

javascript - 空数组的串联如何防止排序突变?

转载 作者:行者123 更新时间:2023-12-01 01:39:05 25 4
gpt4 key购买 nike

空数组的串联arr.concat([])如何防止初始数组发生突变?

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
return arr.concat([]).sort((a, b) => a - b);
}
nonMutatingSort(globalArray);

最佳答案

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

因此,这是创建新数组的快捷方式,它基本上只包含原始数组中的所有内容(加上空数组中的所有内容,即什么都没有)。

关于javascript - 空数组的串联如何防止排序突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52578712/

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