检查JavaScript中的参数名称,而不是值
我试图将if语句放在函数中,其条件基于函数中使用的参数的名称,而不是值 可以利用什么条件来实现这一点?可能吗?如果没有,是否有其他选择 例如:检查JavaScript中的参数名称,而不是值,javascript,variables,if-statement,parameters,Javascript,Variables,If Statement,Parameters,我试图将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){
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?");
}
}
我认为在一般情况下,不可能真正获得变量的名称,因为参数值被复制到函数参数中 也就是说,如果您只有一组固定的变量名,并且正在使用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");
}
另外,您的选择是永远不依赖所传递的变量的名称(谁说甚至有一个变量?)。这是非常不合逻辑的代码。你想解决什么具体问题?我只是通过跟踪迭代来解决它。谢谢你可能想看看这个答案,它已经提到这是可能的。这里使用的概念是动态变量。一定还有别的办法。