gpt4 book ai didi

javascript - 以功能方式交换两个数组元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:54:28 25 4
gpt4 key购买 nike

我正在尝试在 javascript (es6) 中以函数式方式交换数组中的 2 个元素

let arr = [1,2,3,4,5,6]
let result = swap(arr, 1, 2) // input: array, first element, second element
// result=[1,3,2,4,5,6]

我能想到的唯一方法是:

const swap = (arr, a, b) => 
arr.map( (curr,i) => i === a ? arr[b] : curr )
.map( (curr,i) => i === b ? arr[a] : curr )

但是这段代码在数组上运行了两次,而且根本不可读。对漂亮干净的功能代码有什么建议吗?

谢谢。

最佳答案

简短可靠但不可否认难以阅读:

const swap = (x, y) => ([...xs]) => xs.length > 1
? ([xs[x], xs[y]] = [xs[y], xs[x]], xs)
: xs;

const xs = [1,2,3,4,5];

const swap12 = swap(1, 2);

console.log(
swap12(xs),
"exception (one element):",
swap12([1]),
"exception (empty list):",
swap12([])
);

关于javascript - 以功能方式交换两个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42258865/

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