ES6學習筆記(五)--函式與物件
阿新 • • 發佈:2019-02-18
函式
引數的預設值
基本用法
function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello
與解構賦值預設值結合使用
function foo({x, y = 5}) {
console.log(x, y);
}
foo({}) // undefined, 5
foo({x: 1}) // 1, 5
foo({x: 1, y: 2}) // 1, 2
foo() // TypeError: Cannot read property 'x' of undefined
rest引數(…變數名)
rest引數搭配的變數是一個數組,該變數將多餘的引數放入陣列中
function push(array, ...items) {
items.forEach(function(item) {
array.push(item);
console.log(item);
});
}
var a = [];
push(a, 1, 2, 3)
擴充套件運算子(…)
將一個數組轉為用逗號分隔的引數序列
function f(v, w, x, y, z) { }
var args = [0, 1];
f(-1, ...args, 2 , ...[3]);
應用
- 合併陣列
var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];
// ES5的合併陣列
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6的合併陣列
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
- 與解構賦值結合
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
- 符串轉為真正的陣列
[...'hello']
// [ "h", "e", "l", "l", "o" ]
箭頭函式(=>)
var f = v => v;
//等價於
var f = function(v) {
return v;
};
注意
- 函式體內的this物件,就是定義時所在的物件,而不是使用時所在的物件
- 不可以當作建構函式,也就是說,不可以使用new命令,否則會丟擲一個錯誤
- 不可以使用arguments物件,該物件在函式體內不存在。如果要用,可以用Rest引數代替
- 不可以使用yield命令,因此箭頭函式不能用作Generator函式
物件
Object.assign()
用於物件的合併,將源物件(source)的所有可列舉屬性,複製到目標物件(target)
//同名屬性,後面覆蓋前面
var target = { a: 1, b: 1 };
var source1 = { b: 2, c: 2 };
var source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
該方法實行的是淺拷貝,即如果源物件某個屬性的值是物件,那麼目標物件拷貝得到的是這個物件的引用