如何将函数参数转换为键/值对?

时间:2018-08-26 01:31:13

标签: javascript node.js

我正在尝试找到一种使NodeJS成为可能的方法。

a = 10
b = 20
c = 30
d = 40
......
......

function getObject(a, b, c, d, ....) => {

    // this function should return an object.
    // return {
          a : 10,
          b : 20,
          c : 30,
          d : 40,
          .......
          .......
        }
   }

有没有办法在javascript(NodeJS)中做到这一点?

[编辑-已解决]

如{Off this thread中的@Offirmo和注释中的@MarkMeyer所建议,可以使用ES6对象表示法解决问题。

let a = 10;
let b = 20;

function getOject(data){
    console.log(data)
}

getObject({a,b}) // { a: 10, b: 20 }

4 个答案:

答案 0 :(得分:1)

解决方案1:

它应该像这样简单:

Foo!


解决方案2:

在任何函数中获取参数对象的通用方法... 应该可以使用...但是它使用的function test(a,b,c,d){ return {a,b,c,d} } let result= test(1,2,3,4) console.log(result)自ECMAScript 5起就已弃用(但是在大多数主流浏览器中仍然可以使用。)

arguments.callee

答案 1 :(得分:1)

如{Off this thread中的@Offirmo和注释中的@MarkMeyer所建议,可以使用ES6对象表示法解决问题。

function getArgumentsObject(fn,arg){
  let STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  let ARGUMENT_NAMES = /([^\s,]+)/g;  
  let fnStr = fn.toString().replace(STRIP_COMMENTS, '');
  let names = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(names === null) na,es = [];
     
  let obj = {};
  for(let a=0; a<Array.from(arg).length; a++){
    obj[names[a]]=arg[a]
  }
  return obj;
}

function test(a,b,c,d){
  return getArgumentsObject(arguments.callee, arguments);
}

let result = test(1,2,3,4)
console.log(result)

答案 2 :(得分:1)

不,一旦将值传递给函数,该函数将无法访问变量名称。请记住,值可以不带变量名直接传递。

let a = 10;
let b = 20;

function getOject(data){
     console.log(data)
}

getObject({a,b}) // { a: 10, b: 20 }

在es6 +中,您可以创建一个新的对象,如Mark Meyer所述:

const getObject = (a, b, c, d) => ({a, b, c, d})
const foo = 1;
const obj = getObject(foo, 2, 3, 4};
console.log(obj); // {a: 1, b: 2, c: 3 d: 4}

答案 3 :(得分:0)

我建议使用arguments对象。我们将arguments转换为数组,然后基于输出构建对象。要按字母顺序获取键,我们将使用String.fromCharCode()

const foo = function() {
  const _args = [].slice.call(arguments).reduce((obj, key, index) => ({
    ...obj,
    [String.fromCharCode(97 + index)]: arguments[index]
  }), {})

  return _args // { a: 1, b: "hello", c: 2, d: 3, e: "world" }
}

foo(1, 'hello', 2, 3, 'world')