javascript - 在JavaScript中的数组中每n个元素插入一个元素
问题描述
我正在尝试做的事情的前提是:
假设我们有以下数组:
let arr = ["hello", "nice", "stack", "hi", "question", "random"];
我们想要做的是达到一个点,在该点我们可以"cat"
每两个现有的数组元素插入(推入)一个元素到数组中(比如说)。
新数组将产生以下内容:
"hello"
"nice"
"cat" // new element
"stack"
"hi"
"cat" // new element
// so on and so forth...
在减少运行时间的同时实现这一点的最佳方法是什么?
解决方案
使用Array#reduce
:
const
arr = ["hello", "nice", "stack", "hi", "question", "random"],
newElem = "cat",
n = 2;
const res = arr.reduce((list, elem, i) => {
list.push(elem);
if((i+1) % n === 0) list.push(newElem);
return list;
}, []);
console.log(res);
推荐阅读
- java - 标签为JavaFX中的自定义按钮?(通过使用 FXML)
- javascript - js中的二进制操作
- python - Heroku 中的 500 错误,当 Debug=False 时
- ms-access - 导出(4)Forms/Subforms查询和表格数据到Excel
- mongodb - 以一对多模式获取值的总和
- angular - 加载编辑弹出窗口时ngx-datatable非常慢
- mysql - docker commit 不会将更改应用于新创建的 docker 映像
- javascript - 流中的类型与接口索引器属性
- ruby-on-rails - 如何在 Rails 邮件预览中获取 request.host?
- node.js - 将 Nodejs tcp 服务器连接到 websockit