简体   繁体   English

如何在Javascript中将数组元素转换为公式

[英]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.我尝试使用splice()方法,但出了点问题。 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!警告永远不要使用 eval!

The solution lies in stringifying the formula and executing them as it is in javascript.解决方案在于将公式字符串化并像在 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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