我有一些 ES6 代码,我在其中传递了一些已定义选项对象的命名参数,如下所示......
configureMapManager({ mapLocation, configuredWithDataCallback, locationHasChanged })
{
if (mapLocation) console.log(mapLocation)
}
这是一个人为的案例,以下调用将正常工作......
configureMapManager({ mapLocation: "BS1 3TQ" })
configureMapManager({})
但这会爆炸...
configureMapManager()
。因为我无法检查传递的对象是否已定义(这不是因为我调用了没有任何参数的方法(。我怎样才能做到这一点而不必像这样重写它(这很糟糕,因为这样你就失去了对象中允许的参数的可见性(......
configureMapManager(options)
{
if (options && options.mapLocation) console.log(mapLocation)
}
使用默认参数:
function configureMapManager({ mapLocation } = {})
{
console.log(mapLocation);
}
当在没有任何参数的情况下调用函数时,mapLocation
将是未定义的:
configureMapManager(); // prints: undefined
configureMapManager({ mapLocation: 'data' }); // prints: data