JavaScript:获取传递变量的参数值和名称 [英] JavaScript: Get Argument Value and NAME of Passed Variable

查看:23
本文介绍了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".

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

Right now, I have to specify the variable twice:

showName("x", x);

为了得到我传入的变量的名称和值.

In order to get the name and value of the variable I am passing in.

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

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 passed may be local, so I can't use the window object to find the variable.

推荐答案

简短的回答是你不能.

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

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().match(..)[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.

但这仍然非常有限,因为它只会命中 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天全站免登陆