Exception
Exception

Reputation: 8379

Is it possible to achieve array multiplication using this approach

Hi I am trying below method to calculate product of array of numbers.

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

But it returns me NaN.

Is there any other way of doing this.

Upvotes: 3

Views: 738

Answers (2)

Guffa
Guffa

Reputation: 700322

What you are looking for is evaluating the string as an expression:

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

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

Consider just looping instead:

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

Upvotes: 1

Jon
Jon

Reputation: 437376

The ideal would be to use Array.reduce:

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

See it in action.

Array.reduce is not available in IE earlier than version 9, but there should be plenty of implementations to find (e.g. this one).

Upvotes: 4

Related Questions