[英]How to find the sum of the elements of an arbitrary JavaScript array
有這樣一個任意數組,我需要在不使用 Array.isArray 的情況下找到所有數字的總和:
let arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];
解決方案應如下所示:
let arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
你能告訴我如何實現這一目標嗎?
您可以使用Array#flat
和Array#reduce
數組或使用instanceof
運算符檢查給定值的instanceof
。
function getSum1(array) { return array.flat(Infinity).reduce((sum, value) => sum + value, 0); } function getSum2(array) { let sum = 0; for (const value of array) { sum += value instanceof Array ? getSum2(value) : value } return sum; } let array = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]]; console.log(getSum1(array)); console.log(getSum2(array));
使用 flat 和 reduce 方法來實現這一點。
let arr = [[1, 2,
3, [4, 5, [6, 7]]],
[8, [9, 10]]];
arr.flat(Infinity).reduce((a, b) => a + b, 0)
平面: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
減少: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
您為此使用lodash
:
var _ = require("lodash");
var arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];
flatArr = _.flattenDeep(arr);
flatArr.reduce((sum, value) => sum + value, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.