我有一个类似的函数:
function testFunction( option )
{
alert(option);
}
(实际功能不仅仅是回答选项)
当然,如果你这样做的话,它就会起作用 testFunction("qwerty");
,或testFunction(myvar);
,其中myvar
是一个变量。
如果我这样做 testFunction(qwerty);
则不起作用,其中 qwerty 不是一个变量,如预期的那样。
我想知道是否有办法让函数检查是否 option
是一个变量或字符串(例如上面示例中的 "qwerty"
和 myvar
),如果它正常继续并警告字符串或变量的值。
但是,如果它不是变量或字符串,而是 undefined variable (例如上面示例中的 qwerty
),那么我希望它提醒变量的名称(在本例中为 qwerty
) .
这可能吗?
谢谢!
更多示例:
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar); //alerts "1234"
testFunction(qwerty); //alert "qwerty"
最佳答案
你的问题是 testFunction(qwerty);甚至达不到该功能。
Javascript 无法解释变量“qwerty”,因为它没有定义,所以它会在那里崩溃。
只是为了好玩,这里有一种方法可以满足您的要求,通过捕获尝试解释 undefined variable 时抛出的错误:
function testFunction( option ){
console.log(option);
}
try {
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar);
testFunction(qwerty); //alert "qwerty"
}catch(e){
if(e.message.indexOf('is not defined')!==-1){
var nd = e.message.split(' ')[0];
testFunction(nd);
}
}
请记住,您绝对不应该这样做,相反,尝试在程序中使用现有变量,效果会更好;)
关于JavaScript 将变量名转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26202625/