解构赋值与默认值结合使用

1.

function foo({x, y = 5}) {
  console.log(x, y)
}

foo({})
foo({x: 1})
foo({x: 1, y: 2})
foo({y: 3})
foo()

/** output
undefined 5
1 5
1 2
undefined 3
TypeError: Cannot destructure property `x` of 'undefined' or 'null'.
**/

先解构,再赋值,所以当没有传入对象时,会报错

function foo_2({x, y = 5} = {}) {
  console.log(x, y)
}

foo_2()

// undefined 5

2.

function fetch_1(url, { body = '', method = 'GET', headers = {} }) {
  console.log(method)
}

fetch_1('http://example.com', {})

function fetch_2(url, { body = '', method = 'POST', headers = {} } = {}) {
  console.log(method)
}

fetch_2('http://example.com')

fetch_1('http://example.com')

/** output
GET
POST
TypeError: Cannot destructure property `body` of 'undefined' or 'null'.
**/

3. 看个有趣的例子

// 写法一
function m1({x = 0, y = 0} = {}) {
  return [x, y];
}

// 写法二
function m2({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

上面两种写法都对函数的参数设定了默认值,区别是写法一函数参数的默认值是空对象,但是设置了对象解构赋值的默认值;写法二函数参数的默认值是一个有具体属性的对象,但是没有设置对象解构赋值的默认值。

下面是调用情况:

// 函数没有参数的情况
m1() // [0, 0]
m2() // [0, 0]

// x 和 y 都有值的情况
m1({x: 3, y: 8}) // [3, 8]
m2({x: 3, y: 8}) // [3, 8]

// x 有值,y 无值的情况
m1({x: 3}) // [3, 0]
m2({x: 3}) // [3, undefined]

// x 和 y 都无值的情况
m1({}) // [0, 0];
m2({}) // [undefined, undefined]

m1({z: 3}) // [0, 0]
m2({z: 3}) // [undefined, undefined]

Last updated