简体   繁体   中英

How do I turn array elements into formula in Javascript

Elements of the array of a math formula look this way:

a = [1,'+',2,'-',3,'*',4,'/',5];

How do I perform all the arythmetic actions between those numbers. The array elements may be different, because they are added dynamically. (Numbers are all even elements, signs are odd. The first and the last elements are always numbers.)

It would not be difficult if I didn't have to prioritize the actions (/,*,+,-) . I tried using splice() method, but something goes wrong. Maybe I can somehow sort the elements according to the math actions priority?

 var a = [1,'+',2,'-',3,'*',4,'/',5]; console.log(a.join(' '), '=', eval(a.join('')));

eval() docs

WARNING Do not ever use eval!

The solution lies in stringifying the formula and executing them as it is in javascript. You can tweak the solution to fit your needs, but this will work for your case

var a = [1,'+',2,'-',3,'*',4,'/',5];
var b = a.join('');
eval(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM