我下面有函数,想将参数转换为参数与键和值同名的对象
functionA(name, callback, param1, param2, ....paramN)
{
var params = {'param1': param1,.....};
$.ajax(... data: params.....);
}
答案 0 :(得分:0)
基于此措辞的猜测(如果提供更多详细信息,将进行编辑):
如果您在支持ES6的环境中,或者可以通过babel或其他一些编译器来编译代码,则可以这样编写:
function functionA(name, callback, ...params) {
const paramsObj = params.reduce((params, param) => {
return Object.assign(params, {[param]: param});
}, {});
$.ajax({data: paramsObj});
}
functionA(null, null, 'a', 'b'); // paramsObj will be: {a: 'a', b: 'b'}
编辑:如果相反,OP希望键为param1
,param2
等:
function functionA(name, callback, ...params) {
const paramsObj = params.reduce((params, param, i) => {
return Object.assign(params, {[`param${i + 1}`]: param});
}, {});
$.ajax({data: paramsObj});
}
functionA(null, null, 'a', 'b'); // paramsObj will be: {param1: 'a', param2: 'b'}
答案 1 :(得分:0)
一种方法是
function a(p1, p2, p3) {
a = {
[p1]: p1,
[p2]: p2,
[p3]: p3,
}
console.log(a, 'a')
// Gives you
// {a: "a", b: "b", c: "c"}
}
a('a', 'b', 'c')
结合Scott Rudiger的解决方案,您可以做
function functionA(name, callback, ...params) {
var p = params.reduce((obj, item) => {
return obj[item] = item
}, {})
console.log(p)
// Gives you
// {dd: "dd", ee: "ee", ff: "ff", gg: "gg"}
}
functionA('pp', 'cc', 'dd', 'ee', 'ff', 'gg')
答案 2 :(得分:0)
如果我理解正确,这就是您所需要的。
let fnStr = arguments.callee.toString(),
argNames = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(/([^\s,]+)/g), //argNames is a list of parameter names
obj = {};
for(let i= 0; i < arguments.length ; i ++) {
obj[argNames[i]] = arguments[i]
}
答案 3 :(得分:0)
如果您支持ES6,请去rest parameters syntax和Array.reduce()返回对象:
function A(name, callback, ...params)
{
const result = params.reduce((obj, item,i) => {
obj["param"+(i+1)] = item;
return obj;
}, {})
console.log(result);
}
A("name","callback","param1",2,"whatever","param4");
A("name","callback","param1");
旧方法
function A(name, callback, param1)
{
var params = {};
var n = 2;
while( n < Object.keys(arguments).length ){
params["param"+(n-1)] = arguments[n];
n++;
}
console.log(params);
}
A("name","callback","param1",2,"whatever","param4");
A("name","callback","param1");