我有两个数组:
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 5];
我希望最终的数组是:
var arr3 = [3,5,7,9]
如果可能的话,我怎么能用回调来实现呢?
答案 0 :(得分:2)
使用Array.map
(请参阅MDN)
var arrmerge = [1, 2, 3, 4].map(function (v, i) {return v + this[i];}, [2, 3, 4, 5]);
document.querySelector('#result').textContent = JSON.stringify(arrmerge);
<pre id="result"></pre>
答案 1 :(得分:0)
简单地说,
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 5];
var arr3 = [];
var i = 0;
for (; i < arr1.length; i++) {
arr3[i] = arr1[i] + arr2[i];
}
console.log(arr3);
答案 2 :(得分:0)
只需遍历数组并总结值
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 5];
for (i in arr1) {
arr3[i] = arr1[i] + att2[i];
}
&#13;
答案 3 :(得分:0)
您可以查看,
function myFun(){
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 5];
var arr3 = [];
var i = 0;
if(arr1.length == arr2.length){
for (; i < arr1.length; i++)
arr3 [i] = arr1[i] + arr2[i];
console.log(arr3 );
} else{
console.log("Both arrays length are not equal");
}
}