如何将一个数组的值解包到另一个数组的特定索引中?
how to unpack the values of one array into the specific index of another array?
我有以下代码来创建一个简单的机器语言命令数组。
// 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]
数组的末尾保留一些数据。 (换句话说,从索引 2 开始,您的 commands
数组比 cmd[index]
的其余数组短)如果这不是问题,那么只需拼接数组并将您的命令连接到它即可。
我有以下代码来创建一个简单的机器语言命令数组。
// 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]
数组的末尾保留一些数据。 (换句话说,从索引 2 开始,您的 commands
数组比 cmd[index]
的其余数组短)如果这不是问题,那么只需拼接数组并将您的命令连接到它即可。