[英]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)
但是此實現不正確,並且出現了一些錯誤,該怎么辦?
謝謝
使用傳播語法 ...
將數組中的值分配給函數參數:
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)
或使用傳播運算符 : ...
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); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.