spread operator in es6

根據mdn的解釋 the spread syntax allows an expresstion to be expanded in palces where mutiple arguments (for function calls)or multiple elements (for array literals) or multiple variables (for destrucring assignment) are expected
1.在函數調用時用來展開數組到函數的參數express

例子:數組

function add(a, b, c,d) {
    console.log(a + b + c+d)
}
var nums = [34, 21, 2,2]
add(...nums)
//console output 49

2.展開數組到一個數組元素app

var fruits=['apple','pea','cherry']
var foods=['rice',...fruits,'mellon','noddles']
console.log(foods)
//output in command line ['rice','apple','pea','cherry','mellon','noddles']

3.展開對象到一個對象內的屬性(stage 3 draft ,has not been supported util right now)函數

let obj = {
    name: 'Ajaxyz',
    age: 25
}
let objClone = {
    gend: "male",
    ...obj
}
console.log(objClone)
相關文章
相關標籤/搜索