gpt4 book ai didi

javascript - JS 数组中所有项相乘

转载 作者:行者123 更新时间:2023-11-28 15:03:14 25 4
gpt4 key购买 nike

我是 JavaScript 新手,正在闲逛以真正理解基础知识。现在我尝试做一个计算器。一个非常基本的运算,可以加、减、除、乘。我已经让它与此代码一起使用(仅显示乘法:

var multiply = function () {
var numbers = prompt("How many numbers do you want to multiply?","At least 2, max 4");
numbers = Number(numbers);
switch (numbers){
case 2:
num1 = prompt("Your first number: ");
num2 = prompt("Your second number: ");
ans = Number(num1) * Number(num2);
alert(num1 + " * " + num2 + " = " + ans);
break;
case 3:
num1 = Number(prompt("Your first number: "));
num2 = Number(prompt("Your second number: "));
num3 = Number(prompt("Your third number: "));
ans = Number(num1) * Number(num2) * Number(num3);
alert(num1 + " * " + num2 + " * " + num3 + " = " + ans);
break;
case 4:
num1 = Number(prompt("Your first number: "));
num2 = Number(prompt("Your second number: "));
num3 = Number(prompt("Your third number: "));
num4 = Number(prompt("Your fourth number: "));
ans = Number(num1) * Number(num2) * Number(num3) * Number(num4);
alert(num1 + " * " + num2 + " * " + num3 + " * " + num4 + " = " + ans);
break;
default:
alert("Not valid");
break;
}
};
multiply();

我的问题是,当涉及到用户可以相乘的数字数量时,我非常有限。为每个可能的数量制作一个开关盒需要一段时间,所以我想到了这个:

    var multiply = function () {
var numbers = [];
var ans = 0;
var times = prompt("How many numbers do you want to multiply?");
for(var i = 0; i<times; i++){
Number(numbers.push(prompt("Please, enter one of your numbers")));
}
alert(ans);
};
multiply();

所以,我的问题是:如何使“ans”等于数组“numbers”中的每个元素彼此相乘?

最佳答案

您可以使用reduce函数:

[1, 2, 3, 4].reduce(function(a, b) {
return a * b;
}); // it return 24

顺便说一句。在循环中,您应该以这种方式推送到数组:

for(var i = 0; i<times; i++){
numbers.push(Number(prompt("Please, enter one of your numbers")));
}

关于javascript - JS 数组中所有项相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com