make函数从作为参数传入的数组中获取多个变量

时间:2018-05-30 00:19:12

标签: javascript arrays function parameters

如何使函数从作为参数传入的数组中获取多个变量?

  

被修改

例如:

实现这一目标:

const inputObj = [
 ['Anna', 10, 'Monday'],
 ['Anna', 15, 'Wednesday'],
 ['Beatrice', 8, 'Monday'],
 ['Beatrice', 11, 'Wednesday'],
 ['Anna', 4, 'Wednesday'],
 ['Beatrice', 5, 'Monday'],
 ['Beatrice', 16, 'Monday']
]
// expected output:
const outputObj = [ 
[ 'Anna', 10, 'Monday' ],
  [ 'Anna', 19, 'Wednesday' ],
  [ 'Beatrice', 29, 'Monday' ],
  [ 'Beatrice', 11, 'Wednesday' ] 
]

const arr = [0, 2]

const someFunction = (obj, v, a) => {
    const result = obj.reduce((acc, cur) => {
        const key = `${cur[a[0]]}|${cur[a[1]]}`
        if(!acc[key]) acc[key] = cur
        else acc[key][1] += cur[v]
        return acc
      }, {})
    return Object.values(result)
}


console.log(someFunction(inputObj, 1, arr))

用这个:

const arr = [0, 2, 3, ...] // basically the array could contain any number of items.

const someFunction = (obj, v, objParams) => {
      const result = obj.reduce((acc, cur) => {
      const key = ??? 
      ...
      }, {})
}

这样可以重用该函数并接受自定义大小的数组,检查数组中的列号是否相同,然后将传入的列的总和加为v

如何从objParams声明变量以获得与上面代码相​​同的结果?

另外如何在v中间添加cur

2 个答案:

答案 0 :(得分:1)

假设objParams是一个未知大小的数组(本例中为字符串):

const objParams = ["c1", "c2", "c3"];
const key = objParams.join(']}|${cur[');
const built = '${cur[' + key + ']';

建立是:

${cur[c1]}|${cur[c2]}|${cur[c3]

答案 1 :(得分:1)

使用ES6,您可以在参数定义中使用spread运算符。

有关MDN

上的点差运算符的更多阅读

function sum(...args) {
  return args.reduce((result, value) => result + value, 0)
}

const numbers = [1, 2, 3];

console.log('sum', sum(2, 2));
console.log('sum', sum(...numbers));
console.log('sum', sum(1, 2, 1, ...numbers));

// get single args before accumulating the rest
function sum2(foo, bar, ...args) {
  return args.reduce((result, value) => result + value, 0)
}

console.log('sum2', sum2(2, 2));
console.log('sum2', sum2(...numbers));
console.log('sum2', sum2(1, 2, 1, ...numbers));