javascript - 如何将一个数组的值解压到另一个数组的特定索引中?

标签 javascript meteor underscore.js lodash

我有以下代码来创建简单的机器语言命令数组。

// to ensure consistency, initialize an array of values.
var cmd = _.chunk(_.range(0, 300, 0), 30);

_.each(doses, function (dose, index) {
  // these are "headers" to the machine language instructions.
  cmd[index][0] = 1;
  cmd[index][1] = dose.number;

  // this generates the 28 commands to be executed.
  // every four blocks together represents a single command
  var commands = _.flatten(_.map(_.chunk(_.range(0, 28, 0), 4), function (day) {
    _.each(dose.wellIndexes, function (well) {
      day[well] = dose.count.value;
    });
    return day;
  }));
});

(仍在 WIP 代码)。
通过这个 commands 数组,我想将其值解压到 cmd[index][2] 中,以便它将填充数组的其余部分。这可能吗?

查看文档,我发现 merging two arrays ,但这不会替换索引后面的值,只会追加到数组中。

如何在 JavaScript 中将数组值解压到另一个数组中?

最佳答案

如果我正确理解你的问题,a simple mix of splice, concat and apply应该可以解决这个问题:

Array.prototype.splice.apply(cmd[index], [2, commands.length].concat(commands));

也就是说,如果您需要在 cmd[index] 数组的末尾保留一些数据。 (换句话说,您的 commands 数组比从索引 2 开始的 cmd[index] 的其余部分短)如果这不是问题,那么只需拼接数组并将您的命令连接到它。

关于javascript - 如何将一个数组的值解压到另一个数组的特定索引中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31294770/

相关文章:

javascript - 将 Async/Await 函数转换为针对 IE 11 的普通 ES5

javascript - Meteor Http 客户端 API 调用 Gzip 解压缩结果 JSON 不工作

meteor - 容器退出而不是在后台运行

javascript - 分割字符串并找到其结果的有序组合的最优雅的方法

javascript - Parse.com : How to paginate results from a Parse. 查询?

javascript - 如何使用 underscore.js 进行 asc 和 desc 排序?

javascript - 默认情况下选中复选框

javascript - 将 findOne 和 findOneAndUpdate 与 HTTP 请求结合使用 (mongoose)

javascript - 向前和向后浏览时 AJAX 事件消失

node.js - Meteor 和 Socket IO 端口