JavaScript的:获取参数值,并通过变量名 [英] JavaScript: Get Argument Value and NAME of Passed Variable

查看:136
本文介绍了JavaScript的:获取参数值,并通过变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What I want to do is get the NAME of a variable passed to a function and the VALUE of that variable and only have to pass in one variable to the function. So:

var x = "anything";

function showName() {

}

showName(x);

showName("x");

将返回:X =什么

Which will return: "x = anything".

现在,我要做的:

showName("x", x);

为了得到名字,我传递变量的值。请注意,我不感兴趣,在showName的原型参数的名称,但在调用函数的变量的名称。此外,变量可以是本地的,所以我不能使用window对象找到变量。

in order to get the name and value of the variable I am passing in. Note that I am not interested in the name of argument in the prototype of showName, but the name of the variable in the calling function. Also, the variable may be local, so I can't use the window object to find the variable.

推荐答案

简短的回答是,你不能。

The short answer is that you can't.

的时间越长,邪恶的答案是,你那种可以与一些真正的污秽。而且它只能从另一个函数调用时。

The longer, evil answer is that you sort of can with some real nastiness. And it only works when called from another function.

有可用的两个有趣的属性,你可以帮助

there are two interesting attributes available to you that could help

是arguments.callee
来电者

arguments.callee caller

有关FN键做这样的事情:

for fn to do something like this:

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

什么arguments.callee.caller.toString()。比赛(..)[1]确实是去找SHOWME被调用函数中调用它并打印它和它的价值。

What arguments.callee.caller.toString().match(..)[1] does is look for the showMe being called in the function calling it and prints it and its value.

但是这仍然是pretty有限,因为它只会打SHOWME(X)的第一个电话。所以,如果有两个调用它,它不会起作用。

But this is still pretty limited because it will only hit the first call of showMe(x). So if there is two calls to it, it won't work.

但是,很好玩的这些神秘的东西玩了。

But, it was fun to play with these arcane things.

这篇关于JavaScript的:获取参数值,并通过变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆