2

I've got an array [1,2,3] I've just joined it with '+' leaving me with the string

"1+2+3"

How can I evaluate that to get the answer 6.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Panomosh
  • 884
  • 2
  • 8
  • 18

1 Answers1

0

You could use eval:

var result = eval("1+2+3");
Alexander R
  • 2,468
  • 24
  • 28
cari
  • 2,251
  • 2
  • 18
  • 27
  • 1
    eval is evil. Leads to XSS hacks – Ankur Aggarwal Feb 16 '15 at 11:42
  • That is working for what I need it for, I will bear in mind that it's not the best solution @Ankur, thanks. – Panomosh Feb 16 '15 at 11:44
  • it answers the question, no need to downvote here... if he would be able to sum up the array elements before turning them into a string, he would've asked i guess. – cari Feb 16 '15 at 11:45
  • 4
    @AnkurAggarwal Eval is not evil, it can just execute code. Hence you just need to be carefull with your input, just like every other part of your application. Eval does not lead to XSS hacks, just like simply including a 3rd party JS include does not lead to XSS hacks or that a sql query can lead to injections. It is all the same thing. – W van Rij Feb 16 '15 at 11:56
  • Anyways, if you want to avoid using eval for various reasons (Maybe you have to get input from a user?) then you should take a look at PEG.js and write a parser for math expressions – EJTH Feb 16 '15 at 11:57