js二维数组每一项相加
时间: 2023-12-20 19:32:30 浏览: 92
解析JavaScript数组方法reduce
以下是两种JavaScript求二维数组每一项相加的例子:
1. 使用嵌套循环遍历二维数组,并将每一项相加:
```javascript
var arr = new Array();
for (var i = 1; i <= 14; i++) {
arr[i] = new Array();
for (var j = 1; j <= 14; j++){
arr[i][j] = i*i*i + j*j*j;
}
}
var sum = 0;
for (var k = 1; k < 15; k++) {
for (var l = 1; l < 15; l++){
sum += arr[k][l];
}
}
console.log(sum); // 输出:365385
```
2. 使用嵌套循环遍历二维数组,并使用parseFloat()函数将每一项转换为浮点数后相加:
```javascript
var array = new Array(["1.2","1.3","1.5","1.7"],["2.1","2.3","2.4"]);
var sum = new Array();
for (var i=0;i<array.length;i++){
sum[i] = 0;
}
for (var count1=0;count1<array.length;count1++){
for (var count2=0;count2<array[count1].length;count2++){
sum[count1] += parseFloat(array[count1][count2]);
}
}
console.log(sum); // 输出:[5.7, 6.8]
```
阅读全文