帮我用 js reduce 方法实现 [1,2,3,4,5,6,7,8,9] 至 [[1,2,3] , [4,5,6],[7,8,9]] 的转化
时间: 2023-08-19 14:31:14 浏览: 49
好的,这是一个比较简单的操作,您可以使用 `reduce` 方法来实现。代码如下:
```javascript
const arr = [1,2,3,4,5,6,7,8,9];
const result = arr.reduce((acc, cur, index) => {
const subIndex = Math.floor(index / 3);
acc[subIndex] = acc[subIndex] || [];
acc[subIndex].push(cur);
return acc;
}, []);
console.log(result); // [[1,2,3], [4,5,6], [7,8,9]]
```
首先定义了原始数组 `arr`,然后调用 `reduce` 方法,初始值为一个空数组 `[]`。在 `reduce` 方法的回调函数中,我们通过 `Math.floor(index / 3)` 来计算出当前元素应该属于哪个子数组,然后将当前元素 `cur` 添加到该子数组中。最后返回累加器 `acc`。这样就能够将原始数组转化为目标数组了。
相关问题
js实现每个一秒输出1,2,3,使用reduce
这个题目可以用reduce来完成,每次往数组里push下一个数字,然后返回新的数组作为下一次操作的初始值。
具体代码实现如下:
```javascript
const arr = [1,2,3];
arr.reduce((prev, curr) => {
setTimeout(() => {
console.log(curr);
}, prev * 1000);
return prev + 1;
}, 1);
```
解释一下,这里使用了reduce方法,初始值为1,然后每次往数组里push一个数字,要做的事情是设置一个定时器,在prev秒后输出这个数字。
在返回上一个操作的结果时,把当前操作的数字加1,下一次操作使用。
最终效果就是每隔1秒输出一个数字。
js实现每个一秒输出1,2,3,使用reduce和promise
这种情况下,我建议使用 setInterval 和 Promise 来实现,代码如下:
```javascript
function count() {
return new Promise((resolve, reject) => {
let num = 1;
const interval = setInterval(() => {
if (num > 3) {
clearInterval(interval);
resolve();
} else {
console.log(num);
num++;
}
}, 1000);
});
}
count();
```
上面的代码中,我们创建了一个 Promise 对象并返回它,该 Promise 对象的作用是等待定时器完成。在定时器中,我们每隔一秒检查 num 的值,如果 num 大于 3,就清除定时器并解决 Promise。否则,我们将 num 的值打印出来并自增。最后,我们调用 count 函数以开始计数。
阅读全文
相关推荐
















