string => JS中的数字转换

gle*_*ddy 1 javascript

我有一个URL,我在哈希之后解析.哈希之后的内容是一个数学方程式(例如http://example.com/something#5+1),我想找到它的总和(或任何其他方程的结果,如产品,部门等)

我可以使用以下方法检索数字:

var url = (window.location.hash).substr(1) // returns "5+1" as a string
Run Code Online (Sandbox Code Playgroud)

虽然我发现如果我尝试将其转换为数字,它实际上并没有进行数学计算.它将其减少到5,而不是显示8的总和.

这种转换可能吗?

谢谢!

Eli*_*rey 6

不要eval()使用URL中的任意代码,因为它可以很容易地被用于XSS.我创建了一个名为JSandbox的库,可以对JavaScript代码执行进行沙箱化,但它需要对Web worker的支持.对IE使用假工作者支持不是一个好主意,因为沙盒的安全性已经消失.

您的代码如下:

JSandbox.eval("with(Math){" + location.hash.substr(1) + "}", function (res) {
  // handle the results here
});
Run Code Online (Sandbox Code Playgroud)

用它来处理错误:

JSandbox.eval("with(Math){" + location.hash.substr(1) + "}", function (res) {
  // handle the results here
}, null, function (err) {
  // handle errors here
});
Run Code Online (Sandbox Code Playgroud)

我包含了一个with (Math) { ... }包装器,因此哈希代码可以访问Math函数.(例如,abs(..)代替Math.abs(..))