此函数使每个元素自身相乘并输出5040
function multiplyAll(arr) {
var product = 1;
for (var a = 0; a < arr.length; a++) {
for (var b = 0; b < arr[a].length; b++) {
product *= arr[a][b];
}
}
return product;
}
multiplyAll([[1,2],[3,4],[5,6,7]]);
我想要一个显示每个数组中元素相乘的函数(在这种情况下,我希望函数显示[[2],[12],[210]])。
请帮助
答案 0 :(得分:3)
您可以使用.map()
和.reduce()
来实现所需效果,而不会改变输入:
function multiplyAll (array) {
return array.map(
inner => [inner.reduce(
(product, factor) => product * factor
)]
)
}
console.log(multiplyAll([[1,2],[3,4],[5,6,7]]))
&#13;
答案 1 :(得分:1)
function multiplyAll(arr) {
let products = [];
for (var a = 0; a < arr.length; a++) {
let product = 1;
for (var b = 0; b < arr[a].length; b++) {
product *= arr[a][b];
}
products.push([ product ]);
}
return products;
}
multiplyAll([[1,2],[3,4],[5,6,7]]);
只需构建一个新数组并将结果推送到它。
答案 2 :(得分:1)
签出以下代码段,与原始程序相比,其变化最小:
function multiplyAll(arrs) {
var product = 1;
var result = [];
for (var a = 0; a < arrs.length; a++) {
for (var b = 0; b < arrs[a].length; b++) {
product *= arrs[a][b];
}
result.push(product);
product=1;
}
return result;
}
var product = multiplyAll([[1,2],[3,4],[5,6,7]]);
console.log(product);
答案 3 :(得分:0)
检查此解决方案
function multiplyAll(arr) {
return arr.map((inner) => {
let product = 1;
for (let i = 0; i < inner.length; i++) {
product *= inner[i];
}
return [product];
})
}
let product = multiplyAll([[1,2],[3,4],[5,6,7]]);
console.log(product);