我试图将if语句放在一个函数中,条件是函数中使用的参数的名称,而不是值。
可以使用什么条件来实现这一点?有可能吗?如果没有,有没有其他选择?
例如:
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?");
}
}发布于 2017-03-05 03:23:15
我认为在一般情况下不可能获得变量的名称,因为参数值被复制到函数参数中。
也就是说,如果你只有一组固定的变量名,并且你正在使用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");
}https://stackoverflow.com/questions/42600086
复制相似问题