2017-08-09 58 views
3

我有我在哪里传递的定义选项的一些命名参数一些ES6代码对象是这样的...在ES6中命名对象参数 - 如何检查它们是否提供?

configureMapManager({ mapLocation, configuredWithDataCallback, locationHasChanged }) 
{ 
    if (mapLocation) console.log(mapLocation) 
} 

这是一个人为的情况下,和下面的调用将正常工作......

configureMapManager({ mapLocation: "BS1 3TQ" }) 
configureMapManager({}) 

但是,这将炸毁......

configureMapManager() 

...因为我不能检查传入的对象定义(这不是因为我所谓的方法W没有任何参数)。我怎样才能做到这一点,而无需重写这个这样的(这很烂,因为你失去的对象在允许的参数的可见性)......

configureMapManager(options) 
{ 
    if (options && options.mapLocation) console.log(mapLocation) 
} 

回答

4

使用默认参数:

function configureMapManager({ mapLocation } = {}) 
{ 
    console.log(mapLocation); 
} 

当该函数被调用时没有任何参数,mapLocation将被定义为:

configureMapManager(); // prints: undefined 
configureMapManager({ mapLocation: 'data' }); // prints: data 
+0

正是我在找的东西。谢谢@alexmac –

+0

很高兴我的回答帮助你。你能接受答案吗? – alexmac

+0

我正在等待时间到期 - 您必须等待一段时间。 –

相关问题