Javascript:将字符串转换为可计算的



请有人帮助我关于我的javascript代码。我想把字符串转换成可计算的。例子:Var string = 34.5 + 30";

javascript函数或代码将自动计算我的字符串值。因此,结果将是64.5,数据类型为float或decimal。

希望有人能回答我的问题。

使用eval函数

参考

eval()函数计算字符串形式的JavaScript代码。

但是这里有一个安全问题。

从字符串执行JavaScript是一个巨大的安全风险。它是很容易让不良行为者在使用时运行任意代码eval()。参见Never use eval()!,低于.

var myString = "34.5 + 30";
console.log(eval(myString));

由于eval有一些安全问题,所以总是建议不要使用它。您可以使用一些自定义库或实现您自己的解析逻辑。

请从我这边找一个小的配对逻辑。

请注意,这是对数学表达式的线性求值。这个使用BODMAS规则或将不计算任何复杂表达式。这是对只包含数字和基本运算符(如+, -, * and /)的数学表达式求值。如果您希望有自定义验证,您可以在此基础上构建,或者可以实现您自己的解决方案。

我已经添加了描述作为代码注释

const myString = "34.5 + 30";
// Regex to split the expression on +, -, *, / and spaces
const isNumeric = /(?=[-+*/(s+)])/;
// Valid operators
const operators = ['+', '-', '*', '/'];
// Split the string into array
const expressionArray = myString.split(isNumeric);
// Object to hold the result and the operator while parsing the array generated
const result = { result: 0, operator: '' };
// loop though each node in the array
// If an operator is found, set it to result.operator
// If not an operator, it will be a number
// Check an operator is already existing in result.operator
// If then perform the operation with the current node and result and clear the result.operator
expressionArray.forEach((node) => {
const trimmedNode = node.trim();
if (trimmedNode) {
if (operators.indexOf(trimmedNode) === -1) {
if (result.operator) {
switch (result.operator) {
case '+':
result.result += Number(node);
break;
case '-':
result.result -= Number(node);
break;
case '*':
result.result *= Number(node);
break;
case '/':
result.result /= Number(node);
break;
result.operator = '';
}
} else {
result.result += Number(node);
}
} else {
result.operator = trimmedNode;
}
}
});
console.log(result.result);

最新更新