eval语法报错 ie10,JavaScript eval()“语法错误”解析函数字符串

I have a bit of JavaScript code that is specified in a configuration file on the server-side. Since I can't specify a JavaScript function in the configuration language (Lua), I have it as a string. The server returns the string in some JSON and I have the client interpret it using a clean-up function:

parse_fields = function(fields) {

for (var i = 0; i < fields.length; ++i) {

if (fields[i].sortType) {

sort_string = fields[i].sortType;

fields[i].sortType = eval(sort_string);

}

return fields;

}

};

So basically it just evaluates sortType if it exists. The problem is that Firebug is reporting a "Syntax error" on the eval() line. When I run the same steps on the Firebug console, it works with no problems and I can execute the function as I expect. I've tried some different variations: window.eval instead of plain eval, storing the sortType as I've done above, and trying small variations to the string.

A sample value of fields[i].sortType is "function(value) { return Math.abs(value); }". Here's the testing I did in Firebug console:

>>> sort_string

"function(value) { return Math.abs(value); }"

>>> eval(sort_string)

function()

>>> eval(sort_string)(-1)

1

and the error itself in Firebug:

syntax error

[Break on this error] function(value) { return Math.abs(value); }

The last bit that may be relevant is that this is all wrapped in an Ext JS onReady() function, with an Ext.ns namespace change at the top. But I assumed the window.eval would call the global eval, regardless of any possible eval in more specific namespaces.

Any ideas are appreciated.

解决方案

To do what you want, wrap your string in parentheses:

a = "function(value) { return Math.abs(value);}";

b = eval("("+a+")");

b(-1);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值