如何将一个数组的内容迭代到另一个数组的空/未定义位置
How to iterate the contents of one array into the empty/undefined spots of another array?
我有一个数组:
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){
相关文章:
- JavaScript数组包含一个值
- 使用事件更改数组的一个元素
- 从 javascript 数组创建一个 Jquery 数组
- 使用javascript匹配字符串中数组的一个元素
- Angular2从数组创建一个列表
- 在Javascript数组或一个对象中存储多个数据所需的Tweak
- 你能给被劫持的JavaScript数组添加一个函数吗
- 从带有循环的数组中一个接一个地在画布上绘制形状
- 将图像数组从一个窗口传递到另一个窗口,并在javascript的新窗口中显示图像
- 使用拆分字符串的数组创建一个对象
- 多维数组 - 创建一个表
- 将数组从一个函数传递到另一个函数
- 如何将复选框值的数组从一个JSP页面传递到另一个页面
- 使用Knockout.Js将数组绑定到表,并将数组的一个项绑定到另一个元素
- 需要访问数组从一个js到另一个
- 我如何发送数据像数组从一个html文件到另一个html页面
- 从另一个对象和要保存的键数组生成一个对象的最简洁的方法
- 用另一个js数组填充一个javascript数组
- 将对象数组从一个函数传递到另一个函数
- 根据另一个值数组过滤一个对象数组,返回一个空列表