我很想知道是否有 new Array.prototype.<whatever>() 对此有帮助 - flatMap 是这样的......有点 - 但我要离开最简单,最明显的解决方案...
(以及 10 年来没有其他人使用 for 循环构建单个数组的一些眼泪)
普通的旧 JavaScript
如果您要合并立体声通道或模板字符串等内容,这就是您所需要的:
// Supports the two most common cases:
// - interleaving left and right audio channels
// - interleaving template string and values
// (right is assumed to be the same length as left, or one shorter)
function interleave(left, right) {
var both = [];
var i;
for (i = 0; i < left.length; i += 1) {
both.push(left[i]);
// because a template string will have one fewer value
// than it will have string parts
if (i < right.length) {
both.push(right[i]);
}
}
return both;
}
// a template string will always have one extra item
var abc = ['a', 'b', 'c', 'd' ];
var one = [1, 2, 3 ];
var both = interleave(abc, one);
console.log(both);
// ['a', 1, 'b', 2, 'c', 3, 'd']
平面地图
正如评论中提到的,这可能是合适的:
function cleverInterleave() {
return abc.flatMap(function (val, i) {
if (one[i]) {
return [val, one[i]];
}
return [val];
});
}
var abc = ['a', 'b', 'c', 'd' ];
var one = [1, 2, 3 ];
cleverInterleave(abc, one);
// ['a', 1, 'b', 2, 'c', 3, 'd']
然而,这似乎有点过于“聪明”,而且不像 直观。效率也不高……但对于大多数代码来说,可读性远比效率重要,所以……有两个打击。
mo' 频道,mo' 问题
您还可以创建一个更通用的形式来处理任意数量的数组,或者压缩长度不均匀的数组。
但是,我建议使用类似的模式,但要根据您需要的实际阵列数量进行调整 - 例如 3 个用于 RGB,或 4 个用于 RGBA,等等。