gpt4 book ai didi

javascript - 这个reduce函数是使用spread还是rest?

转载 作者:行者123 更新时间:2023-12-02 21:28:17 24 4
gpt4 key购买 nike

我在区分传播和休息时遇到了一些困难。有人可以向我解释一下reduce函数返回语句中是否使用了spread或rest吗?

这是我不明白的:

return [currentValue, ...accumulator]

内部

let str = 'KING';

const reverseStr = str => {
return str
.split('')
.reduce((accumulator, currentValue) => {
return [currentValue, ...accumulator];
}, [])
.join('');
};

最佳答案

Rest 语法总是创建(或分配)一个变量,例如:

const [itemOne, ...rest] = arr;
// ^^ created ^^^^

扩展语法仅产生另一个数组(或对象)表达式 - 它不会将任何内容放入变量中。在这里,您使用扩展语法创建一个由 currentValueaccumulator 的值组成的新数组。

return [currentValue, ...accumulator];

就像

return [currentValue, accumulator[0], accumulator[1], accumulator[2] /* ... */];

您将累加器的项分散到返回的数组中。

关于javascript - 这个reduce函数是使用spread还是rest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60680428/

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