用另一个数组中的特定元素替换数组元素

时间:2014-11-03 14:18:48

标签: javascript arrays

所以我尝试使用javascript实现合并排序,我遇到的问题是我无法用排序子数组中的值替换原始数字数组。

我在类似的问题中看到了以下解决方案:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var anotherArr = [ 1, 2, 3 ];

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));

console.log(arr);

输出:

[ 1, 2, 3, 'd', 'e', 'f', 'g', 'h', 'i', 'j']

但是,所有 anotherArr的元素将被放入arr

我是否可以指定我想要插入arr的元素?

1 个答案:

答案 0 :(得分:-1)

假设您只想覆盖元素1和3

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var anotherArr = [ 1, 2, 3 ];
var overwrite = [true, false, true];

for(var i = 0; i < anotherArr.length; i++){
    if(overwrite[i] == true) arr[i] = anotherArr[i];
}

alert(arr);

输出:arr = [ '1', 'b', '3', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

链接到fiddle

相关问题