将变量从 javascript 转移到 math.js (getElementById())
Transfer variables from javascript to math.js (getElementById())
我正在尝试将 javascript 变量传输到 math.js 函数。通过getElementById获取变量(denexp)如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/mathjs@6.2.2/dist/math.min.js"></script>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<canvas id=canvas1 width=1600 height=400></canvas>
<canvas id=canvas2 width=800 height=400></canvas>
<table>
<tr>
<th>den</th>
<th><input type="number" id="denid" value="1.0" min="0"> </th>
</tr>
</table>
<script>
const sim = math.parser()
const denexp = document.getElementById("denid").value;
sim.evaluate("G = denexp") // Density
</script>
</body>
</html>
不过,math.js
似乎无法读取 denexp
我收到以下错误:
Uncaught Error: Undefined symbol denexp
你有什么想法吗?
在您传递给 evaluate
的字符串 ("G = denexp"
) 中,Math.js 期望仅查找数字、单位和数学符号之类的内容:0.5
、sin
、sqrt
、deg
等。您试图通过简单地将变量 denexp
包含在字符串中来传递它,但 "denexp"
不是一个符号Math.js 明白了。相反,您必须将 denexp
的 value 附加到字符串:
sim.evaluate("G = " + denexp)
或者如果您的浏览器目标支持模板文字:
sim.evaluate(`G = ${denexp}`)
或者,您可以为 Math.js 提供范围,这将允许您在表达式中使用范围内定义的任何变量:
var scope = {
denexp: denexp
}
sim.evaluate("G = denexp", scope)
这样做的好处是任何变量赋值(例如此处的 G =
)也将保存到作用域中(尽管像您的示例中所做的那样简单地将一个变量赋值给另一个变量不是很有用并且可能不是你想要的)。
我正在尝试将 javascript 变量传输到 math.js 函数。通过getElementById获取变量(denexp)如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/mathjs@6.2.2/dist/math.min.js"></script>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<canvas id=canvas1 width=1600 height=400></canvas>
<canvas id=canvas2 width=800 height=400></canvas>
<table>
<tr>
<th>den</th>
<th><input type="number" id="denid" value="1.0" min="0"> </th>
</tr>
</table>
<script>
const sim = math.parser()
const denexp = document.getElementById("denid").value;
sim.evaluate("G = denexp") // Density
</script>
</body>
</html>
不过,math.js
似乎无法读取 denexp
我收到以下错误:
Uncaught Error: Undefined symbol denexp
你有什么想法吗?
在您传递给 evaluate
的字符串 ("G = denexp"
) 中,Math.js 期望仅查找数字、单位和数学符号之类的内容:0.5
、sin
、sqrt
、deg
等。您试图通过简单地将变量 denexp
包含在字符串中来传递它,但 "denexp"
不是一个符号Math.js 明白了。相反,您必须将 denexp
的 value 附加到字符串:
sim.evaluate("G = " + denexp)
或者如果您的浏览器目标支持模板文字:
sim.evaluate(`G = ${denexp}`)
或者,您可以为 Math.js 提供范围,这将允许您在表达式中使用范围内定义的任何变量:
var scope = {
denexp: denexp
}
sim.evaluate("G = denexp", scope)
这样做的好处是任何变量赋值(例如此处的 G =
)也将保存到作用域中(尽管像您的示例中所做的那样简单地将一个变量赋值给另一个变量不是很有用并且可能不是你想要的)。