JavaScript 中在函数参数中使用解构

Posted by cl9000 on May 15, 2020

设计是品牌无声的形象大使。——<兰德·保罗>

在函数参数中使用 ES6 Destructuring Assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

1
2
3
4
5
6
var sayHello = function({ name, surname }) {
console.log(`Hello ${name} ${surname}! How are you?`);
};

sayHello({ name: 'John', surname: 'Smith' })
// -> Hello John Smith! How are you?

这对于接受选项对象的函数非常有用。对于此用例,您还可以添加默认参数以填写呼叫者遗漏的任何值,或者如果呼叫者根本忘记传递一个值:

1
2
3
var sayHello2 = function({ name = "Anony", surname = "Moose" } = {}) {
console.log(`Hello ${name} ${surname}! How are you?`);
};
1
2
3
4
sayHello2()
// -> Hello Anony Moose! How are you?
sayHello2({ name: "Bull" })
// -> Hello Bull Moose! How are you?

参数处理

使用简单的析构分配,如果输入参数无法与函数的指定对象参数匹配,则所有不匹配的参数均为undefined,因此您需要添加正确处理此代码的代码:

1
2
3
4
5
6
7
8
var sayHelloTimes = function({ name, surname }, times) {
console.log(`Hello ${name} ${surname}! I've seen you ${times} times before.`);
}

sayHelloTimes({ name: "Pam" }, 5678)
// -> Hello Pam undefined! I've seen you 5678 times before.
sayHelloTimes(5678)
// -> Hello undefined undefined! I've seen you undefined times before.

更糟糕的是,如果缺少要分解的参数,则会引发异常,可能会使您的应用程序停止运行:

1
2
sayHelloTimes()
// -> Uncaught TypeError: Cannot match against 'undefined' or 'null'...

它在概念上类似于访问未定义对象的属性,只是具有不同的异常类型。

使用默认参数进行销毁分配会在一定程度上隐藏以上所有内容:

1
2
3
4
5
6
7
8
9
10
var sayHelloTimes2 = function({ name = "Anony", surname = "Moose" } = {}, times) {
console.log(`Hello ${name} ${surname}! I've seen you ${times} times before.`);
};

sayHelloTimes2({ name: "Pam" }, 5678)
// -> Hello Pam Moose! I've seen you 5678 times before.
sayHelloTimes2(5678)
// -> Hello Anony Moose! I've seen you undefined times before.
sayHelloTimes2()
// -> Hello Anony Moose! I've seen you undefined times before.

至于= {},它涵盖了缺少对象的情况,对于该对象,单个属性的默认设置根本无济于事:

1
2
3
4
5
6
7
8
9
10
var sayHelloTimes2a = function({ name = "Anony", surname = "Moose" }, times) {
console.log(`Hello ${name} ${surname}! I've seen you ${times} times before.`);
};

sayHelloTimes2a({ name: "Pam" }, 5678)
// -> Hello Pam Moose! I've seen you 5678 times before.
sayHelloTimes2a(5678)
// -> Hello Anony Moose! I've seen you undefined times before.
sayHelloTimes2a()
// -> Uncaught TypeError: Cannot match against 'undefined' or 'null'.

可用性
请注意,默认情况下,在您使用的Node.js或浏览器版本中,销毁分配可能尚不可用。对于Node.js,您可以尝试–harmony-destructuring在启动时使用该标志来激活此功能。

参考

关注【公众号】,了解更多。



支付宝打赏 微信打赏

赞赏一下 坚持原创技术分享,您的支持将鼓励我继续创作!