如何使用ES6中的所有默认值对选项参数进行破坏? [英] How to destructure option argument with all default values in ES6?
本文介绍了如何使用ES6中的所有默认值对选项参数进行破坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,它将选项对象作为参数:
function myFunction({option1 = true,option2 = 'whatever'}){
console.log(option1,option2);
//做某事...
}
当我打电话给它时,破坏发生,一切顺利。
我想在大多数时候用默认选项调用它,所以我做:
myFunction({}) ; // true'whatever'
但它看起来有点奇怪。只要打电话就会更清晰:
myFunction(); // TypeError:无法读取未定义的属性'option1'
可以吗?
解决方案
是的,您只需为完整的参数提供默认值:
function myFunction({option1 = true,option2 ='whatever'} = {}){
// ^^^^
控制台.log(option1,option2);
//做某事...
}
I use ES6 features with babel compiler. I have a function which takes option object as an argument:
function myFunction({ option1 = true, option2 = 'whatever' }) {
console.log(option1, option2);
// do something...
}
When I call it, destructuring happens and everything works well. I want to call it with default options most of the time, so I do:
myFunction({}); // true 'whatever'
but it looks little bit strange. It would much more cleaner just call:
myFunction(); // TypeError: Cannot read property 'option1' of undefined
Is it possible?
解决方案
Yes, you just have to provide a default value for the complete argument:
function myFunction({option1 = true, option2 = 'whatever'} = {}) {
// ^^^^
console.log(option1, option2);
// do something...
}
这篇关于如何使用ES6中的所有默认值对选项参数进行破坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文