gpt4 book ai didi

JavaScript : Make an array of value pairs form an array of values

转载 作者:搜寻专家 更新时间:2023-11-01 04:56:12 25 4
gpt4 key购买 nike

是否有一种优雅、实用的方式来转动这个数组:

[ 1, 5, 9, 21 ]

进入这个

[ [1, 5], [5, 9], [9, 21] ]

我知道我可以forEach 数组并收集值以创建一个新数组。在 _.lodash 中是否有一种优雅的方法可以在不使用 forEach 的情况下做到这一点?

最佳答案

您可以映射拼接数组并检查索引。如果不为零,则取前导,否则取原数组的第一个元素。

var array = [1, 5, 9, 21],
result = array.slice(1).map((a, i, aa) => [i ? aa[i - 1] : array[0], a]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

一个更短的版本,如 Bergi 所建议的那样:

var array = [1, 5, 9, 21],
result = array.slice(1).map((a, i) => [array[i], a]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于JavaScript : Make an array of value pairs form an array of values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44161735/

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