Javascript eval ReferenceError:未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24001442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript eval ReferenceError: is not defined
提问by user3577459
I need to dynamical create a variable off the value of a variable from an argument I am pulling in from a script. But I first want to check if it already exists so I don't overwrite it, if it is already set.
我需要从我从脚本中提取的参数的变量值动态创建一个变量。但我首先想检查它是否已经存在,所以我不会覆盖它,如果它已经设置。
I am leveraging eval to expand the value of the variable and tag it onto a variable suffix but no matter what I use to check for the undefined I am getting a reference error on the check.
我正在利用 eval 扩展变量的值并将其标记为变量后缀,但无论我使用什么来检查未定义,我都会在检查中收到引用错误。
Below is the simple code snippet
下面是简单的代码片段
chkUser = args[1];
if(typeof eval(chkUser+"lastseen")==="undefined") ;
I've also tried put the eval in parens and putting undefined in ' ' and pulled them completely and switching typeof to the JavaScript standard undefined as such
我还尝试将 eval 放在括号中并将 undefined 放在 ' ' 中并完全拉动它们并将 typeof 切换为未定义的 JavaScript 标准
if( eval(chkUser+"lastseen")=== undefined) ;
but I always get ReferenceError: robertlastseen is not defined or what ever chkUser expands out to.
但我总是收到 ReferenceError: robertlastseen is not defined 或者 chkUser 扩展到什么。
回答by Nano
Its just a gues, but it seems like the Variable is just not defined before you eval it.
它只是一个猜测,但在您评估它之前似乎没有定义变量。
try this Fiddle.
试试这个小提琴。
It works fine for me.
这对我来说可以。
Try to hardcode the variable before you eval it like this:
在像这样评估变量之前尝试对变量进行硬编码:
chkUser = args[1];
var robertlastseen = 'Hardcode';
console.log(eval(chkUser+"lastseen"));
Then you shoud be able to debug your code.
然后你应该能够调试你的代码。
if you just want to test if this Variable is declared try this:
如果您只想测试此变量是否已声明,请尝试以下操作:
if(eval('typeof ' + chkUser + 'lastseen') === "undefined"){
//Variable undefined
}