JavaScript:获取参数值和传递变量的名称

46 javascript arguments

我想要做的就是传递给函数的变量的名称该变量的值,并且只在一个变量传递给函数.所以:

var x = "anything";

function showName() {

}

showName(x);
Run Code Online (Sandbox Code Playgroud)

要么

showName("x");
Run Code Online (Sandbox Code Playgroud)

将返回:"x =任何东西".

现在,我必须指定变量两次:

showName("x", x);
Run Code Online (Sandbox Code Playgroud)

为了获取我传入的变量的名称和值.

请注意,我对showName原型中的参数名称不感兴趣,但是对调用函数中的变量名称不感兴趣.另外,传递的变量可能是本地的,所以我不能使用window对象来查找变量.

Bar*_*cat 59

简短的回答是,你做不到.

更长,更邪恶的答案是你可以带着一些真正的肮脏.它只在从另一个函数调用时才有效.

有两个有趣的属性可供您使用

arguments.callee调用者

为fn做这样的事情:

(function(){
  var showMe = function(s){
    alert(arguments.callee.caller.toString().match(/showMe\((\S)\)/)[1] + 
    ' = '+ s)
  }
  x = 1
  showMe(x)
})()
Run Code Online (Sandbox Code Playgroud)

arguments.callee.caller.toString().match(..)[1]的作用是查找在调用它的函数中调用的showMe并打印它及其值.

但这仍然非常有限,因为它只会触及showMe(x)的第一个调用.因此,如果有两个调用它,它将无法正常工作.

但是,玩这些神秘的东西很有趣.

  • +1,令人厌恶和迷人. (53认同)

Red*_*ter 8

var x = "anything";

function showName(s) {
    alert(s + " = " + eval(s));
}

showName("x");
Run Code Online (Sandbox Code Playgroud)

不推荐,但确实如此.


小智 6

策略1:

如果你可以在函数调用期间控制数据结构,那么你可以传递一个字典,它将name作为键编码,与其值配对,注意隐形花括号:

var foo = "bar";
yourfunction({foo});
Run Code Online (Sandbox Code Playgroud)

这传递了一个如下所示的javascript字典:

{foo : "bar"}
Run Code Online (Sandbox Code Playgroud)

yourfunction(被执行时,解包名称和值thustly:

yourfunction = function(dict) { 
    var name = Object.keys(dict)[0];
    var value = dict[name];
    console.log(name);        //prints foo
    console.log(value);       //prints bar
}
Run Code Online (Sandbox Code Playgroud)

策略2:

如果您可以在全局范围内维护名称 - 值对的即用列表,则可以为set和get提供反射和内省,例如:

var my_global_stack = [];

yourfunction = function() { 

    //Chomp the stack
    var dict = my_global_stack.pop();

    //The name is the key at index 0
    var name = Object.keys(dict)[0];

    //Fetch the value by keyname:
    var value = dict[name];

    console.log(name);       //prints foo
    console.log(value);      //prints bar
}


foo = "bar";
my_global_stack.push({foo});
yourfunction();
Run Code Online (Sandbox Code Playgroud)

策略3:

如果用户恶意输入不是问题,您可以使用eval(重新发现给定variablename的值,例如:

yourfunction = function(somevariable) { 
    console.log(somevariable);          //prints foo
    console.log(eval(somevariable));    //prints bar
}

foo = "bar";
yourfunction("foo");
Run Code Online (Sandbox Code Playgroud)

人们说eval(这里很邪恶,因为如果恶意用户能够foo在任何时候覆盖内存中的值,那么他们就可以执行OS命令注入并运行他们想要的任何命令.
http://cwe.mitre.org/top25/#Guidance