2017-03-04 90 views
0

我试图将if语句置于一个函数内,并且条件基于函数中使用的参数的名称,而不是值。在JavaScript中检查参数名称,而不是值

什么条件可以用来实现这一目标?可能吗?如果没有,是否有替代方案?

例如:

var lorem="The name is Lorem, but the value isn't."; 
var ipsum="The name is Ipsum, but the value isn't."; 
//the values shouldn't matter 

logIt(Lorem); 

function LogIt(theName){ 
    if(**the name of the variable theName = "lorem"**){ 
    console.log("The variable 'lorem' was used."); 
    }else if(**the name of the variable theName = "ipsome"**){ 
    console.log("The variable 'ipsum' was used."); 
    }else{ 
    console.log("huh?"); 
    } 
} 
+0

另外,你选择将是永远不要依赖传递的变量的名称(谁是说那里甚至有一个?)。这是非常不合逻辑的代码。 –

+0

你想解决什么具体问题? –

+0

我通过简单地跟踪迭代来解决它。谢谢! – kennsorr

回答

0

我相信这是不是真的可能得到在一般情况下,变量的名称,因为参数复制到函数参数。

也就是说,如果你只有一组固定的变量名和您正在使用ES6,你可以在技术上“黑客”与周围物体解构的问题:

var lorem="The name is Lorem, but the value isn't."; 
var ipsum="The name is Ipsum, but the value isn't."; 

Logit({lorem}) 

function Logit({lorem, ipsum}) { 
    if(lorem) console.log("Function called with lorem"); 
    else if(ipsum) console.log("Function called with ipsum"); 
    else console.log("Function called with something else"); 
} 
+0

那么你可能想看看这个答案它已经提到,这是可能的http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript。这里使用的概念是动态变量。还有一些其他的方法。 – rresol

相关问题