[英]How to add elements of array within an array in JavaScript?
我們如何在JavaScript的數組內添加數組的元素? 好像我有類似的東西
positions=[[1,2],[2,7],[3,9]]
如何獲得主數組中每個數組中第一個元素的總和,數組中每個數組中第二個元素的總和。 所以我想計算
x1=1+2+3
y1=2+7+9
一個簡單的for
循環就足夠了,也將是最有效的解決方案和得到最廣泛支持的解決方案(此處提出的所有其他解決方案都將在較舊的瀏覽器上失效,除非使用polyfilled):
var x1 = 0, y1 = 0, len = positions.length;
for (var i = 0; i < len; i++)
{
x1 += positions[i][0];
y1 += positions[i][1];
}
或者,您可以使用forEach
方法:
var x1 = 0, y1 = 0;
positions.forEach(function(a) { x1 += a[0]; y1 += a[1]; });
但是,如果您想花哨的話,可以使用reduce
方法,如下所示:
var x1 = positions.reduce(function(x, a) { return x + a[0]; }, 0);
var y1 = positions.reduce(function(x, a) { return x + a[1]; }, 0);
alert([x1, y1]); // 6,18
您甚至可以像這樣一次計算兩個和:
var xy = positions.reduce(function(x, a) { return [x[0] + a[0], x[1] + a[1]]; }, [0, 0]);
alert(xy); // 6,18
我為你做了些小提琴。 看看這個。 它應該回答您的問題。
http://jsfiddle.net/rkhadse_realeflow_com/xTup9/16/
<script>
var positions = [
[1, 2],
[2, 7],
[3, 9]
];
console.log(positions[1][1]);
var i = 0;
var output = "";
for (i = 0; i < positions.length; i++) {
output = output + "(" + positions[i][0] + "," + positions[i][1] + ")";
}
console.log(output);
var x1 = 0;
var y1 = 0;
for (i = 0; i < positions.length; i++) {
x1 = x1 + positions[i][0];
y1 = y1 + positions[i][1];
}
console.log(x1);
console.log(y1);
</script>
帶有注釋的代碼:
var positions = [[1,2],[2,7],[3,9]]; // Create your array of numbers
x1 = y1 = 0; // Baseline x1 and y1
// Loop through your array (this is standard for loop)
for (var i = 0, len = positions.length; i < len; i++) {
x1 += positions[i][0]; // Add first array element to existing count
y1 += positions[i][1]; // Add second array element to existing count
}
// Log results
console.log(x1);
console.log(y1);
這是一個工作示例: http : //jsfiddle.net/6ras8/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.