Math.js eval函数在传入字符串与非字符串参数时表现不一致
null in Math.js 4.0.1 eval with String Expressions I get exactly what you're dealing with—this quirk between direct JS expressions and string inputs in Math.js can be super frustrating when you need to use custom functions that require string parsing. Let's break down why this happens and fix it.
Why the Difference?
When you pass an unquoted expression like math.eval(1 + null):
- JavaScript itself first evaluates
1 + nullbefore passing anything to Math.js. Sincenullgets implicitly converted to0in arithmetic operations, Math.js ends up just processing the number1, which works perfectly.
But when you pass the same expression as a string (math.eval("1 + null")):
- Math.js uses its own expression parser, which doesn't recognize
nullas a valid numeric constant by default. It treatsnullas an undefined variable, hence the error.
Solutions to Fix This
Since you need to use string expressions for custom functions, here are a few reliable ways to handle null:
Replace
nullwith0in the string
Use a simple string replacement to swap out any instances ofnullwith0before passing it tomath.eval:const originalExpr = "1 + null * myCustomFunc(5)"; const processedExpr = originalExpr.replace(/\bnull\b/g, "0"); const result = math.eval(processedExpr);The regex
\bnull\bensures you only replace whole-word instances ofnull, avoiding accidental matches in function names or variables.Import
nullas a constant into Math.js
Tell Math.js to recognizenullas a value equal to0by importing it as a custom constant:// Import null as 0, overriding any existing definition math.import({ null: 0 }, { override: true }); // Now this works without modification const result = math.eval("1 + null"); // Returns 1 const customResult = math.eval("myCustomFunc(null) + 3"); // Uses your func with 0 instead of nullThis is great if you have lots of expressions with
nulland don't want to manually replace them every time.Handle
nulldirectly in your custom functions
If your custom functions might receivenullas input, add logic inside them to handle it:math.import({ myCustomFunc: function(input) { // Convert null to 0 (or whatever default makes sense for your use case) const sanitizedInput = input === null ? 0 : input; // Your function logic here return sanitizedInput * 2; } }); // Now this works seamlessly const result = math.eval("myCustomFunc(null) + 1"); // Returns 1
Pick the approach that fits your workflow best—all of these will let you keep using string expressions with custom functions while avoiding the null error.
内容的提问来源于stack exchange,提问作者Goofy

