简体   繁体   English

函数内部的访问参数名称字符串

[英]Access argument name string inside the function

Is it possible to access arguments name strings?! 可以访问参数名称字符串吗?

function myFunction (a, b, c, d, e, f) {
    var obj = [];
    [].forEach.call(arguments, function(arg) {
        obj.push({
            // question is how to get variable name here?
            name: "a",// "a", "b", "c", "d", "e", "f"
            value: arg, //a, b, c, ,d, e, f
        })
    });
 return obj;
}

myFunction(1,2,3,4,5,6); // return [{name: "a", value: 1}, {name: "b", value: 2}...]

Note: I know using arguments is not a good practice. 注意:我知道使用arguments不是一个好习惯。 I want to know if this even possible or not? 我想知道这是否可能吗?

You could try something like this: 您可以尝试这样的事情:

function myFunction (a, blabla, c, somethingElse, e, f) {
    var obj = [];
    //'(a, b, c, d, e, f)' 
    var tmp = arguments.callee.toString().match(/\(.*?\)/)[0];
    //["a", "b", "c", "d", "e", "f"] 
    var argumentNames = tmp.replace(/[()\s]/g,'').split(',');

    [].splice.call(arguments,0).forEach(function(arg,i) {
        obj.push({
            // question is how to get variable name here?
            name: argumentNames[i],
            value: arg
        })
    });
    return obj;
}

console.log(JSON.stringify(myFunction(1, 2, 3, 4, 5, 6)));
//Output-> [{"name":"a","value":1},{"name":"blabla","value":2},
//          {"name":"c","value":3},{"name":"somethingElse","value":4},
//          {"name":"e","value":5},{"name":"f","value":6}]

DEMO DEMO

Are the function parameter names definied in the function definition, as you've written above? 如上所写,函数定义中是否定义了函数参数名称? If so, you can just create an array in the function: 如果是这样,您可以在函数中创建一个数组:

function myFunction(a,b,c,d,e,f) {
  var argNames = ['a','b','c','d','e','f'];
  ...
}

arguments will only ever contain a simple array of the arguments passed to the function. arguments仅包含传递给函数的参数的简单数组。 There is no default mapping from arguments to parameter names. 从参数到参数名称没有默认映射。 That I'm aware of anyway 我仍然知道

This works: 这有效:

function myFunction( _obj ) {

    var obj = [],
        names = [],
        args = arguments,
        len = function(o) {
            var a = [];

            for (var i in o) a.push(i);

            return a;
        };

    for (var i in _obj) names.push( i );

    [].forEach.call( len(_obj), function(a, b) {
        obj.push({
            name: names[b],
            value: args[0][names[b]]
        });
    });

    return obj;

}

console.log( myFunction({
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6
}));​​​​

Here is a DEMO 这是一个演示

For completeness: you can't use named parameters in javascript. 出于完整性考虑:您不能在javascript中使用命名参数 If you want to use them (and thus be able to identify the parameter names), a workaround is to supply an object: 如果要使用它们(从而能够识别参数名称),则一种解决方法是提供一个对象:

function myParams(params){
  var ret = [];
  for (var l in params){ 
   if (params.hasOwnProperty(l)){
    ret.push(l);
   }
  }
  return ret
}
myParams({a:1,b:2,c:3,d:null,e:null,f:null,g:11});
//=> [a,b,c,d,e,f,g]

See also... 也可以看看...
And to be really complete: see this also 要真正完成: 请参阅此

You can invoke toString on the function and then use some kind of RegEx to parse result. 您可以在函数上调用toString,然后使用某种RegEx解析结果。



    function someFunction(a,b,c){}
    var functionString = someFunction.toString(); //return "function someFunction(a,b,c){}"
    var args = functionString.match(/^function (?:.*?)\((.*?)\)/);
    if(args[1])
    {
        var argsNames = args[1].split(",");
    }

I've tested it on FF and Chrome. 我已经在FF和Chrome上进行了测试。

Since item.product_image2 is a URL string, you need to put it in quotes when you call changeImage inside parameter. 由于item.product_image2是URL字符串,因此在参数内部调用changeImage时需要将其放在引号中。

My Function Onclick 我的功能

items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+"  onclick='changeImage(\""+item.product_image2+"\");'>";

My Function 我的功能

<script type="text/javascript">
function changeImage(img)
 {
    document.getElementById("saleDetailDivGetImg").src=img;
    alert(img);
}
</script>

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

相关问题 然后在该函数中调用promise的内部访问函数参数 - Access to fuction argument inside then of promise called in that function 如何在箭头功能内访问Argument对象 - How to access Argument object inside arrow function 将变量作为参数传递给另一个函数后,能否以字符串形式访问变量的名称? - Can I access a variable's name as a string after passing it as an argument to another function? 获取作为函数参数的变量名作为字符串 - getting variable name which is a argument of the function as a string 通过函数内部的字符串访问变量 - Access variable by string inside function 为什么在函数内部创建同名变量时不会覆盖函数参数? - Why is the function argument not overwritten on creating variable of same name inside the function? 使用JavaScript中的参数更改函数内部的命名空间数组名称 - Change namespaced array name inside function using argument in JavaScript 如何调用其中可以通过此函数访问参数的函数? - how to invoke function that inside it you can access to argument through this? 如何使控制器中的函数访问指令内部的参数? - How to make a function in a controller access an argument that's inside a directive? 如何在 function 内部传递一个作为访问属性的参数 - How to pass inside a function an argument which is an access properties
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM