如何将一个数组的内容迭代到另一个数组的空/未定义位置

How to iterate the contents of one array into the empty/undefined spots of another array?

本文关键字:数组 另一个 迭代 位置 未定义 一个      更新时间:2023-09-26

我有一个数组:

var myArray = [2, 4, 6];

和另一个数组:

var otherArray = [1, , 3, , 5, , 7];

我试图映射(或使用任何非"for/for-each"迭代器)将每个myArray值放入otherArray的相应空白空间。

希望输出:

newArray = [1, 2, 3, 4, 5, 6, 7];

任何想法?

otherArray.forEach(function (val, idx) {
    if (typeof val === 'undefined') {
        otherArray[idx] = myArray.shift();
    }
});

forEach可能不兼容,如果支持IE <9。

使用Array.prototype.map:

var newArray = otherArray.map(function(val) {
    return typeof val === 'undefined' ? myArray.shift() : val;
});

请注意,这不会触及从未设置过的索引。

使用while循环:

while (myArray.length > 0) {
  var emptyIdx = otherArray.indexOf();
  otherArray[emptyIdx] = myArray.shift();
}

编辑:好吧,如果数组中的元素真的没有设置,就像你描述的那样,这些解决方案将不起作用,因为它们会跳过未设置的索引。下面是一个可行的方法:

var myArray = [2, 4, 6, 8, 9];
var otherArray = [1, , 3, , 5, , 7];
var lastIdx = -1;
otherArray.forEach(function(val, idx) {
  if (idx - lastIdx > 1) {
    otherArray[idx - 1] = myArray.shift();
  }
});
if (myArray.length > 0) {
  otherArray = otherArray.concat(myArray);
}
document.body.innerHTML = otherArray;

您可以遍历数组并检查未定义的值,如:

var otherArray = [1, , 3, , 5, , 7];
var myArray = [2, 4, 6];
for (var i = 0, j = 0; i < otherArray.length; i++) {
    //check if a value is undefined
    if (!otherArray[i]) {
        //then change this value with the new from other array
        otherArray[i] = myArray[j];
        j++;
    }
}
console.log(otherArray);//prints [1, 2, 3, 4, 5, 6, 7]

您可以使用递归,该函数将用第二个数组的项填充第一个数组的undefined项,直到它到达所使用的其中一个数组的末尾。

var otherArray = [1, , 3, , 5, , 7];
var myArray = [2, 4, 6];
function fillArray(ar1, ar2, i){
    if (!i) i = 0;
    if (!ar1[i]){
        ar1[i] = ar2.shift();
    }
    if (++i < ar1.length && ar2.length > 0){
        fillArray(ar1, ar2, i);   
    }
}
fillArray(otherArray, myArray); // this will update the content of originals arrays, 
// use otherArray.slice() to get a copy.
document.getElementById("result").innerHTML = JSON.stringify(otherArray);
<div id="result"></div>


如果您想添加元素(因为myArray中有其他项目,otherArray中没有剩余空间),您可以更改条件以继续用||替换&&

if (++i < ar1.length || ar2.length > 0){