JavaScript 将变量名转换为字符串

标签 javascript string variables undefined alert

我有一个类似的函数:

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);
    }
}   

JSFiddle here

请记住,您绝对不应该这样做,相反,尝试在程序中使用现有变量,效果会更好;)

关于JavaScript 将变量名转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26202625/

相关文章:

php - 如何将 PHP 变量从一个函数传递到另一个函数?

Windows 批处理脚本问题 - 引用包含空格的变量

javascript - 点击链接,div滑出,链接div滑入,点击关闭重新加载第一个div

Mysql group by 包含空格作为相同的值

javascript - 需要根据某种逻辑对Javascript数组进行排序

c - 使用 scanf 忽略分隔字符

string - 列表[字符串] -> 矢量[矢量[字符]]

java - Java中类之间传递变量

javascript - if 语句中多个 OR 表达式的简写

javascript - 如何使用 jqplot 更改饼图的圆圈大小?