gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:20:09 24 4
gpt4 key购买 nike

是否可以访问参数名称字符串?!

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}...]

注意:我知道使用 arguments 不是一个好习惯。我想知道这是否可能?

最佳答案

你可以尝试这样的事情:

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

关于javascript - 访问函数内的参数名称字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11194181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com