问题描述
我有一些JavaScript代码在服务器端的配置文件中指定。由于我无法在配置语言(Lua)中指定JavaScript函数,因此我将它作为字符串。服务器返回一些JSON中的字符串,并让客户端使用清理函数来解释它:
parse_fields = function字段){
for(var i = 0; i< fields.length; ++ i){
if(fields [i] .sortType){
sort_string = fields [i] .sortType;
fields [i] .sortType = eval(sort_string);
}
返回字段;
}
};
所以基本上它只是评估 sortType
存在。问题在于Firebug在 eval()
行上报告了语法错误。当我在Firebug控制台上运行相同的步骤时,它可以正常工作,我可以按照我的预期执行该功能。我尝试了一些不同的变体: window.eval
而不是简单的 eval
,存储 sortType
,正如我上面所做的那样,并尝试对字符串进行细微的变化。
$ b
字段的示例值[ i] .sortType
是function(value){return Math.abs(value);}
。以下是我在Firebug控制台中进行的测试:
>>> sort_string
function(value){return Math.abs(value);}
>>> eval(sort_string)
function()
>>> eval(sort_string)( - 1)
1
和Firebug中的错误本身:
语法错误
[关于这个错误的函数] function(value){return Math.abs(value); }
最后一点可能相关的是,它全部用Ext JS onReady()
函数,并在顶部更改 Ext.ns
命名空间。但我认为 window.eval
会调用全局 eval
,而不管任何可能的 eval
任何想法都可以使用。
解决方案 a =function(value) {return Math.abs(value);};
b = eval((+ a +));
b(-1);
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);
这篇关于JavaScript eval()“语法错误”解析函数字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!