javascript:获取在函数中传递的实际参数的名称 [英] javascript: get names of actual arguments passed in a function

查看:35
本文介绍了javascript:获取在函数中传递的实际参数的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以知道函数中传递的实际参数的名称吗?像

Can we know the name of actual arguments passed in the function? like

func(a,b,c,d); 

当我们称此为我要在输出中打印a,b,c,d时.如果我将func定义为

when we call this I want a,b,c,d printed in output. Something like if I define func as

function func(e,f,g,h) {
// do something here so that
console.log('something');//prints a,b,c,d as output
}

以下操作无法完全达到目的,但是如果在与该问题相关的javascript中无法执行任何操作,则以下操作可以作为答案.看,是否有人可以解决这个问题?

Following does not serve the purpose completely but if nothing can be done in javascript related to this question then following can be an answer. See, if anyone can build around this?

function func(){
    var args = Array.prototype.slice.call(arguments),result='';

        for(var i in this){

            if(args.indexOf( this[i])!==-1 ){
                result+=i+',';
                }

        }

    console.log(result);
    }

所以,如果我打电话给我

so, if I call like,

var a=22, b=46, c=99;
func.call(this,a,b,c);//or func(a,b,c)

将打印a,b,c但

在以下情况下,它将失败:

in following case it will fail:

var w=4,a=4, b=4, c=99;

然后输出将是a,b,c,w,这是错误的,因为w不是传递的参数.

then output will be a,b,c,w which is wrong as w is not the argument passed.

看看,是否有人可以解决这个问题?

See, if anyone can build around this?

推荐答案

我需要这样做,因为名称还包含我的函数逻辑中需要的一些信息

I need that because the names also contain some information which I need in my function logic

如果我调用func(a,b,c,d),那么如果func中的逻辑存在一个流程,如果我使用func(l,m,n,d)进行调用,那么func算法中的逻辑流程就会发生变化,因此输出也会改变

if i call func(a,b,c,d) then there is one flow if logic in func and if I call it with func(l,m,n,d) then the logic flow in func algorithm changes and accordingly the output will change too

您对JS的理解或您对问题的看法,或者更可能是两者,都存在严重的错误.

There is something profoundly wrong with your understanding of JS, or your conception of your problem, or more likely both.

函数不知道,不知道,也必须不知道,也没有理由要知道在调用它们时使用了哪些变量,值或表达式.

我不知道这是否可以解决您的问题,但是请考虑执行以下操作:

I have no idea if this will solve your problem, whatever it is, but consider doing the following instead:

func({a,b,c,d}); 

{a,b,c,d} 格式创建一个键为 a 等的对象,其值是变量 a .这是ES6语法.在ES5中:

The {a,b,c,d} format creates an object with keys of a etc. whose values are the variable a. This is ES6 syntax. In ES5:

func({a: a, b: b, c: c, d: d}); 

然后,您可以在函数中查看作为参数传入的对象中的键.

Then, in your function, you can look at the keys in the object passed in as a parameter.

这篇关于javascript:获取在函数中传递的实际参数的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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