我试图以下列方式添加两个不同的数组。
A = [1 2 3 4] B = [2 3 4 5]
A + B = [3 5 7 9]
<script>
function myFunction1(){
var Mmax1 = new Array();
var Mmax2 = new Array();
var L = document.getElementById("txt1").value;
var w = document.getElementById("txt2").value;
var P = document.getElementById("txt3").value;
var a = document.getElementById("txt4").value;
for (var x = 0; x <= L; x += 1) {
sum[x] = x
Mmax1[x] = w * x / 2 * (L-x)
Mmax2[i] = P*a*(i-a)/i;
}
Mmax = Mmax1 + Mmax2
</script>
如何在Javascript中完成? 谢谢!
答案 0 :(得分:1)
我们想确保数组不为空且长度相同......然后我们可以迭代。
var A = [1, 2, 3, 4], B = [2, 3, 4, 5]
var sum = [];
function sumArray(a, b) {
if (a != null && b != null && a.length == b.length) {
for (var i = 0, len = a.length; i < a.length; i++) {
sum.push(a[i] + b[i]);
}
}
return sum;
}
console.log(sumArray(A, B));
答案 1 :(得分:0)
使用Array#map
方法。
var A = [1, 2, 3, 4],
B = [2, 3, 4, 5];
var res = A
// iterate over first array
.map(function(v, i) {
// sum up first array value and second
// array value fetched by index
return v + B[i];
});
console.log(res);
答案 2 :(得分:-1)
var AB=[];
for(var x in A){
AB.push(A[x]+B[x]);
}
console.log(AB);