ES6,擴展運算符
阿新 • • 發佈:2019-02-12
log 運算符 後置 定義 同名 function 遍歷屬性 per defined
ES6,擴展運算符
1.數組(擴展運算符)
解構賦值
擴展運算符(spread)就是我們知道的三個點(...),它就好像rest參數的逆運算,將一個數組轉為用逗號分隔的參數序列。
console.log(...[1,2,3]);
//1 2 3
console.log(1,...[2,3,4],5)
//1 2 3 4 5
console.log([1,...[2,3,4],5])
//[1, 2, 3, 4, 5]
[...document.querySelectorAll(‘div‘)]
// [<div>, <div>, <div>]
復制數組
let arr = [1, 2], arr1 = [...arr]; console.log(arr1); // [1, 2]
// 數組含空位
let arr2 = [1, , 3],
arr3 = [...arr2];
console.log(arr3); [1, undefined, 3]
合並數組
console.log([...[1, 2],...[3, 4]]); // [1, 2, 3, 4]
// 本質也是:**將一個數組轉為用逗號分隔的參數序列,然後置於數組中**
2.對象
拓展運算符(...)用於取出 參數對象 所有 可遍歷屬性 然後拷貝到當前對象。
基本用法
let person = {name: "Amy", age: 15}; let someone = { ...person }; console.log(someone); //{name: "Amy", age: 15}
合並對象
let age = {age: 15};
let name = {name: "Amy"};
let person = {...age, ...name};
person; //{age: 15, name: "Amy"}
註意:自定義的屬性在拓展運算符後面,則拓展運算符對象內部同名的屬性將被覆蓋掉。同理,自定義的屬性在拓展運算度前面,則變成設置新對象默認屬性值。
let person = {name: "Amy", age: 15}; let someone = { ...person, name: "Mike", age: 17}; let someone1 = { name: "Mike", age: 17,...person}; console.log(someone); //{name: "Mike", age: 17} console.log(someone1); //{name: "Amy", age: 15}
拓展運算符後面是空對象、null、undefined,沒有任何效果也不會報錯。
//空對象
let a = {...{}, a: 1, b: 2};
console.log(a); //{a: 1, b: 2}
// null 、 undefined
let b = {...null, ...undefined, a: 1, b: 2};
console.log(b); //{a: 1, b: 2}
3.函數
不定參數用來表示不確定參數個數,形如,...變量名,由...加上一個具名參數標識符組成。具名參數只能放在參數組的最後,並且有且只有一個不定參數。
基本用法
function f(...values){
console.log(values.length);
}
f(1,2); //2
f(1,2,3,4); //4
function addNumbers(x,y,z){
return x+y+z;
}
var numbers = [1,2,3,4];
addNumbers(...numbers); //6
//函數調用中,擴展運算符(...)將一個數組,變為參數序列
擴展運算符與政策的函數參數可以結合使用,非常靈活:
function f(x,y,z,v,w){
console.log(x,y,z,v,w)
}
var args = [0,1,5];
var args1 = [0,1];
f(-1,...args,2,...[3]);//-1, 0, 1, 5, 2
f(-1,...args1,2,...[3]);//-1, 0, 1, 2, 3
ES6,擴展運算符