ES6 预设参数 (Default parameters)
过去都要先自行检查是否为 undefined使用预设参数后 传入参数 undefined => 使用预设值使用预设参数后 传入参数 null,0,'' => 使用传入值
function foo(x = 100) { console.log(x) } foo() // 100 foo(undefined) // 100 foo(null) // null // babel 版本 function foo() { // 过去都要自行判断 该值是否为 undefined var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; console.log(x); }
预设参数可以被后方的预设参数取用
function foo(bar = 50, baz = bar + 50) { console.log(baz) } foo() // 100
亦可搭配 ES6 解构方式来撰写
function faz([x, y] = [1, 2], { z } = { z: 3 }) { return x + y + z } faz() // 6 const [x, y] = [1, 2] const { z } = { z: 3 } console.log(typeof x) // number console.log(typeof z) // number
无法将函式设为预设参数
// 此方法无法执行 会造成 ReferenceError function fuk(a = go()) { function go() { return ':P' } } fuk()
Rest Operator
用于不知道要传入多少参数ESLint 不推荐使用 arguments
function add(...numbers) { console.log(numbers) // [1, 2, 3] console.log(typeof numbers) // object 阵列也是物件 return numbers.reduce((sum, el) => sum + el, 0) } console.log(add(1, 2, 3)) // 6
Spread Operator
用于展开阵列合併组成阵列合併组成物件
const arrA = ['AAA', 'AA', 'A'] const arrB = ['BBB', ...arrA] // 合併阵列 ["BBB", "AAA", "AA", "A"] console.log(arrB) //* Array Concat 作法 const arrC = ['CCC'] // 合併阵列 ["CCC", "AAA", "AA", "A"] console.log(arrC.concat(arrA))
const oldObj = { title: 'oldTitle', newAttr: 'oldAttr',}//* 创造新物件,并加入新属性const newObj = { name: 'newObj', // 当 newObj 没有该属性,则加入新属性 // 当 oldObj 没有该属性,就会採用此 default title: 'default', // default ...oldObj, }const newObjCreated = { name: "newObj", // 来自 newObj 原本的属性 title: "oldTitle", // 来自 oldObj 的覆盖 newAttr: "oldAttr" // 来自 oldObj 新属性}console.log(newObj)