简体   繁体   English

将变量作为参数传递给另一个函数后,能否以字符串形式访问变量的名称?

[英]Can I access a variable's name as a string after passing it as an argument to another function?

Perhaps a slightly dim question but I'm trying to design something where I'm using javascript / jquery to change the layout of a website and I'd like to see the values of both a variable name and it's current value in another div. 也许是一个有点模糊的问题,但是我正在尝试设计一些我使用javascript / jquery更改网站布局的地方,我想在另一个div中查看变量名和它的当前值。

I was just doing $test.append('example string' + exampleVar) a lot so I thought I would make a function called test(). 我只是在做$test.append('example string' + exampleVar)很多,所以我想我会做一个叫做test()的函数。

So far I have: 到目前为止,我有:

function test (test) {
    $test = $('.test');
    $test.append(test+"<br>");
}

and then would pass it a variable name as an argument but I can't find any way of making it display the name as a string. 然后将变量名作为参数传递给我,但是我找不到任何方法将其显示为字符串。 I know about making it as an object to access the key and value but that doesn't really seem to work here? 我知道将它作为访问键和值的对象,但这似乎在这里真的行不通吗?

Bit of a long-winded way to do it, but here's an example using an object: 有点费劲的方法,但这是使用对象的示例:

function tester(options) {
  var keys = Object.keys(options);
  console.log(keys[0] + ': ' + options[keys[0]]); // test: My value
}

tester({ test: 'My value' });

DEMO 演示

In a function you will be using a parameter. 在函数中,您将使用参数。 So in that case the "variable name" will always be the name of the parameter. 因此,在这种情况下,“变量名称”将始终是参数的名称。 In this case getting the string value will always be test. 在这种情况下,将始终测试字符串值。 I would assume this is not what you want. 我认为这不是您想要的。 You were correct that the best way to do this is to use an object and iterate over the key, values. 您是正确的,执行此操作的最佳方法是使用一个对象并遍历键值。 You would do this like: 您将这样做:

var test = {
    "test" : "value"
};
function test (test) {
    var k, $test = $('.test');
    for(k in test){
        $test.append(k + "<br>");
    }
}

Also, I do not think there is a way to get the variable string name. 另外,我认为没有办法获取可变字符串名称。 So the above would be the way to get the name of a variable. 因此,以上就是获取变量名称的方法。

You could use a feature of javascript where obj["prop"] is the same as obj.prop 您可以使用javascript obj["prop"]obj.prop相同的功能

So instead of passing the variable as a variable and hoping to get its name, you use the name as a string to get the variable's value. 因此,您可以将名称用作字符串来获取变量的值,而不是将变量作为变量传递并希望获得其名称。

If you aren't using namespaces/variables and want to a global/root variable, pass window, eg: 如果您不使用名称空间/变量,而是想要全局/根变量,请传递窗口,例如:

function test(obj, val) {
    console.log(val + ": " + obj[val]);
}

var val1 = 1;
var val2 = 2;

test(window, "val1");
test(window, "val2");

(obviously you don't get the name of 'obj' - but maybe it's a start) (显然,您没有获得“ obj”的名称-但这也许只是一个开始)

if you only have root/global variables (as in the example provided in the question) then you could remove obj: 如果您只有根/全局变量(如问题中提供的示例所示),则可以删除obj:

function test(val) {
    console.log(val + ": " + window[val]);
}

var val1 = 1;
var val2 = 2;

test("val1");
test("val2");

It seems what you want to do something like this: 看来您想要执行以下操作:

var argumentName = /([^\s,]+)/g;
// fu is a function
// fu.toString look like: function myFunction (param[, param]*)  { code }
function getParamNames(fu) {
    var f = fu.toString();
    return f.slice(f.indexOf('(')+1,f.indexOf(')')).match(argumentName);
}

Then you might want to create an helper which will take every functions: 然后,您可能需要创建一个将执行所有功能的助手:

// I choosed the console as an output, but you can set anything
function displayParameters(fu) {
    var _params = getParamNames(fu);
    if(_params!==null) {
        for(var i=0;i<_params.length; i++) {
            console.log(_params[i]);
        }
    } else { console.log('no parameters'); }
}

And, you will need to call: displayParameters(test); 并且,您将需要调用: displayParameters(test);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM