如何将数组的键分配为函数的参数?
How to assign a keys of an array as a function's parameters?
我有一个 JavaScript 模块,它使用带有 3 个参数的箭头函数导出,如下示例:
// getMonth.js 模块
export default (date, type, ...rest) => {
// Represent this return exmaple
return date + ' ' + type + ' ' + rest
}
在主文件中,我有一个数组,我想将数组的键指定为函数的参数
import getMonth from '../modules/month.js'
let splitedParams = ['2016/07/14', 'full']
getMonth({date, type, ...rest} = splitedParams)
但是这个实现不正确,我遇到了一些错误,我该怎么做?
谢谢
使用 spread syntax ...
将数组中的值赋给函数参数:
import getMonth from '../modules/month.js'
const splitedParams = ['2016/07/14', 'full']
getMonth(...splitedParams)
import getMonth from '../modules/month.js'
let splitedParams = ['2016/07/14', 'full']
getMonth.apply(null, splitedParams)
或使用spread operator:...
getMonth(...splitedParams)
请参阅下面的示例:
let splitedParams = ['2016/07/14', 'full']
//using Function.prototype.apply()
getMonth.apply(null, splitedParams);
//using the spread operator
getMonth(...splitedParams);
function getMonth(date, type) {
console.log('getMonth() - date: ', date, 'type: ', type);
}
我有一个 JavaScript 模块,它使用带有 3 个参数的箭头函数导出,如下示例:
// getMonth.js 模块
export default (date, type, ...rest) => {
// Represent this return exmaple
return date + ' ' + type + ' ' + rest
}
在主文件中,我有一个数组,我想将数组的键指定为函数的参数
import getMonth from '../modules/month.js'
let splitedParams = ['2016/07/14', 'full']
getMonth({date, type, ...rest} = splitedParams)
但是这个实现不正确,我遇到了一些错误,我该怎么做?
谢谢
使用 spread syntax ...
将数组中的值赋给函数参数:
import getMonth from '../modules/month.js'
const splitedParams = ['2016/07/14', 'full']
getMonth(...splitedParams)
import getMonth from '../modules/month.js'
let splitedParams = ['2016/07/14', 'full']
getMonth.apply(null, splitedParams)
或使用spread operator:...
getMonth(...splitedParams)
请参阅下面的示例:
let splitedParams = ['2016/07/14', 'full']
//using Function.prototype.apply()
getMonth.apply(null, splitedParams);
//using the spread operator
getMonth(...splitedParams);
function getMonth(date, type) {
console.log('getMonth() - date: ', date, 'type: ', type);
}