跳到主要内容

解构-函数参数

1. 数组参数

  • 数组下标与参数下标一一对应
function test([a, , [b], c]) {
logd(a, b, c)
}

test([5, null, [6]]) // 输出: 5 6 undefined

2. 字符串参数

function test([a, b, c]) {
logd(a, b, c)
}

test("ab") // 输出: a b undefined

3. 对象参数

function test({c, x: d, e}) {
logd(c, d, e)
}

test({c: 7, x: 8}) // 输出: 7 8 undefined

4. 嵌套参数

function test([e, {x: f, g}], {h, x: [i]}) {
logd(e, f, g, h, i)
}

test([9, {x: 10}], {h: 11, x: [12]}) // 输出:9 10 undefined 11 12

5. arguments 用法

function test({a, x: b, y: e}, [c, d]) {
logd(arguments[0].a, arguments[0].x, arguments[1][0], arguments[1][1])
}

test({a: 1, x: 2}, [3, 4]) // 输出: 1 2 3 4
  • 空参数
function test({}, []) {
logd(arguments[0].a, arguments[0].x, arguments[1][0], arguments[1][1])
}

test({a: 1, x: 2}, [3, 4]) // 输出: 1 2 3 4

6. 函数参数长度length

function test({a, b}, {c, d}) {
}

logd(test.length) // 输出: 2

7. 默认值

function test({a = 1, b = 0, c = 3, x: d = 0, y: e = 5}, [f = 6, g = 0, h = 8]) {
logd(a, b, c, d, e, f, g, h)
}

test({b: 2, c: undefined, x: 4}, [, 7, undefined]) // 输出: 1 2 3 4 5 6 7 8

8. 箭头函数

let test = (a, {b: x = 0, c: y = 3}) => {
logd(a, x, y)
}

test(1, {b: 2}) // 输出: 1 2 3