Is it possible to achieve array multiplication using this approach

Hi, I am trying to use a method to calculate the product of an array of numbers.

 var str = [1,2,3];
 alert(str.join('*') * 1);​

But he brings me back NaN.

Is there any other way to do this.

+3
source share
2 answers

Ideal would be to use Array.reduce:

alert(str.reduce(function (acc, curr) { return acc * curr; }, 1));

Look in action .

Array.reducenot available in IE earlier than version 9, but there must be many implementations to search for (like this one ).

+4
source

What you are looking for evaluates the string as an expression:

alert(eval(str.join('*')));​

However, as always, if you use eval, you should seriously ask yourself that you are doing something wrong.

Instead, consider just a loop:

var result = 1;
for (var i = 0; i < str.length; i++) result *= str[i];
alert(result);
+1
source

All Articles