是否可以通过分解设置一些默认参数,同时仍然保留默认值中未考虑的任何额外值?例如:
var ob = {speed: 5, distance: 8}
function f({speed=0, location='home'}) {
return {speed: speed, location: location, /* other keys passed in with their values intact */}
}
f(ob) // Would like to return {speed: 5, location: 'home', distance: 8}
编辑:我的功能是不知道可能会传递额外的键的名称。例如:该函数不知道它将接收/返回一个名为“ distance”的键还是一个名为“ foo”的键。所以我正在考虑某种形式的...休息,然后再使用...传播。
最佳答案
您无法使用当前的es6,但可以使用通过阶段2预设提供的rest运算符。
function f({speed= 0, location: 'home', ...others}) {
return Object.assign({}, {speed, location}, others);
}