[英]How to add the first element of this nested array
我有這個嵌套數組
let thirarray = [
[2, 3, 4],
[5, 6, 7, 8],
[9, 10],
];
我想要做的是添加每個數組的第一個元素所以基本上添加 2+5+9=16 我知道我可以像這樣訪問每個元素
//this is how i can access the first element of each array
console.log(thirarray[0][0]);
console.log(thirarray[1][0]);
console.log(thirarray[2][0]);
我知道我可以使用嵌套循環訪問所有這樣的元素
let suminsidearrays = 0;
for (i = 0; i < thirarray.length; i++) {
for (let j = 0; j < thirarray[i].length; j++) {
console.log(thirarray[i][j]);
suminsidearrays += thirarray[i][j];
console.log(suminsidearrays);
}
}
所以我的問題是如何添加每個數組的第一個元素?
這將對主數組中每個數組的第一個元素求和。
const array = [[2, 3, 4],[5, 6, 7, 8],[9, 10]] let sum = array.reduce((a,c)=>a+c[0],0) console.log(sum)
更新評論中的新模式要求。
const array = [[2, 3, 4],[5, 6, 7, 8],[9, 10, 11]] let i = 0, sum = array.reduce((a,c)=>a+c[i++],0) console.log(sum)
最簡單的方法
let thirarray = [[2, 3, 4],[5, 6, 7, 8],[9, 10]]; var res=0 thirarray.forEach(a=>res+=a[0]) console.log(res)
我只想補充一點,我能夠使用從@holydragon 學到的東西來解決它。 所以這就是我所做的
let fourthrarray = [
[20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120, 130],
];
let nextindexposition = 0;
let nextto = 0;
let sumeelsegundo = 0;
for (let i = 0; i < fourthrarray.length; i++) {
//this will allow me to see the 1st index position from each array
//i should expect to see 20,50,90
sumeelsegundo = fourthrarray[i][0];
//this will add the first index position of each array expected output will be 160
sumeelsegundo += fourthrarray[i][0];
console.log(sumeelsegundo);
//in order to add the next index position from each array i used two variable
//one that will store the result and the other one that will increase the index
//position by one on every iteration. this one will allow me to see the elements
//that will be added. expected elements will be 20,60,110
nextto = fourthrarray[i][nextindexposition++];
//this will be adding the elements expected output expected output 190
nextto += fourthrarray[i][nextindexposition++];
console.log(nextto);
}
只是為了澄清一下這個解決方案適用於添加數字,如果我想相乘,我只需將變量 nextto 的起始值從 0 更改為 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.