将数组JS中的所有项相乘
Multiply all items in an Array JS
我是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();
所以,我的问题是:我怎样才能让"answers"等于我的数组"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")));
}
如其他答案所述,您可以使用Array.reduce
方法。除了滚动自己的乘法函数,还可以使用本地Math.imul
方法:
var numbers = [1, 2, 3, 4];
var ans = numbers.reduce(Math.imul);
console.log(ans);
如果我理解正确的话,你想要像乘法([1,2,3,4])=== 24这样的东西?然后可以使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
您可以继续请求一个数字,同时显示中间结果。用户可以使用转义退出:
var multiply = function () {
var s, ans = 1;
while (s = prompt('Current product is ' + ans +
'. Enter next factor to multiply with, or hit escape to exit')) {
ans *= Number(s);
}
}
multiply();
Reduce可能是正确的答案,但是为了让您更全面地了解它实际在做什么,请看下面的示例。这就是我如何手动做基本相同的事情,增加一些警卫,使其更安全。
//This is an enum. It's basically a cleaner and more
//scalable way to define constants. Here I'm using an
//integer to represent each of the four operations
var OPERATIONS = {
'ADD': 1,
'SUBTRACT': 2,
'MULTIPLY': 3,
'DIVIDE': 4
};
function calc (operation, values)
{
if (!operation || !values || values.length < 2)
{
//The inputs aren't valid, so throw some kind of error
}
//This will be used in all of our cases, so
//we define it at a larger scope
var result;
switch (operation)
{
case OPERATIONS.MULTIPLY:
//Extracts the first value and stores it
result = values.shift ();
//Iterate through the remaining values.
//Remember that the first value is no
//longer in the set
values.forEach (function (value, index)
{
//*= is a unary operator which multiplies a value by
//the operand, and then stores it back in itself.
//This is equivalent to result = result * value.
result *= value;
});
break;
//Create cases for ADD, SUBTRACT, and DIVIDE
}
return result;
}
//Test cases
console.log (calc (OPERATIONS.ADD, [1, 1]); //Prints 2
console.log (calc (OPERATIONS.SUBTRACT, [10, 1, 1]); //Prints 8
console.log (calc (OPERATIONS.MULTIPLY, [1, 2, 3, 4]); //Prints 24
console.log (calc (OPERATIONS.ADD, [calc (OPERATIONS.MULTIPLY, [5, 5], 3, 100]); //Prints 128
如果你想做这样的事情,你可以让它更一般化一点…
function calc2 (operations, values)
{
//You need one more value than operation here
if (!operations || !values || values.length < 2 || (values.length - operations.length !== 1))
{
//The inputs aren't valid, so throw some kind of error
}
var result = values.shift ();
while (values.length)
{
switch (operations[0])
{
case OPERATIONS.ADD:
result += values[0]
break;
case OPERATIONS.SUBTRACT:
result -= values[0]
break;
case OPERATIONS.MULTIPLY:
result *= values[0]
break;
case OPERATIONS.DIVIDE:
result /= values[0]
break;
default:
//Something has gone horribly wrong. Thrown an error
}
//Work your way down the array by continually
//removing the first value
values.shift ();
operations.shift ();
}
//Note that this method solves the equation linerally;
//BEDMAS (or PEMDAS, depending on where you're from)
//is not honoured.
return result;
}
//Test cases
console.log (calc ([OPERATIONS.ADD], [1, 1])); //Prints 2
console.log (calc ([OPERATIONS.ADD, OPERATIONS.ADD], [1, 2, 3])); //Prints 6
console.log (calc ([OPERATIONS.ADD, OPERATIONS.ADD, OPERATIONS.DIVIDE], [6, 7, 5, 3])); //Prints 6
第二个函数将通过逐个存储输入和操作来使用。所以你得到像6 + 7 + 5 / 3 =
这样的东西,然后你把它分解成它的各个组成部分来做计算。
这里的一般方法是,您想要获得一个基本值,然后在其上迭代以获得最终结果。在第一种情况下,这意味着对每个值使用相同的操作来改变值。在第二种情况下,您告诉它您希望在每一步而不是在开始时执行的突变类型。
如果您想将其推广到使用BEDMAS或具有更复杂的功能,则可能必须创建一个树结构,其中每个节点代表一个操作及其各自的操作数,并且只需遍历树即可获得结果。
。PLUS(PLUS(DIVIDE(5, 3), 7), 6)
- 在数组JS中查找三个重复项
- 比较二维数组js
- 从数组(JS)中的对象调用函数
- 检查对象是否已被推入数组 Js
- 将CSV文件转换为JSON数组JS
- 解析多维数组JS的数组并记录索引
- 如何遍历直接传递到灰尘的数组.js
- 如何使用 D3 选择 JSON 数组.js 使用 .算子
- JavaScript 变量中的 PHP 数组 - JS 元素
- 将数据复制到 JavaScript D3 中的数组.js然后绘制散点图
- 基于数组JS中的值创建按钮
- 创建数组JS
- 按频率排序子字符串数组-JS
- 将数组js变量传递给php
- 使用不带嵌套循环的数组过滤对象数组js
- 创建封装数组JS
- 创建多dim数组(JS)
- 创建for循环对象并将它们压入数组js中
- 将数组JS中的所有项相乘
- 如何从二维数组(JS)中获取网格的坐标