在对象解构中使用默认值,同时保留任何非默认值
Using default values in object destructuring while retaining any un-defaulted values
是否可以通过解构设置一些默认参数,同时仍然保留默认值中未考虑的任何额外值?例如:
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}
编辑:我的函数不知道可能作为附加项传入的键的名称。例如:该函数不知道它是 receiving/returning 一个名为 'distance' 的键还是一个名为 'foo' 的键。所以我在考虑某种使用...rest 然后...spread。
您不能使用当前的 es6,但您可以使用通过第 2 阶段预设提供的 rest 运算符。
function f({speed= 0, location: 'home', ...others}) {
return Object.assign({}, {speed, location}, others);
}
Is it possible to set some default parameters via destructuring while still retaining any extra values not accounted for in the default?
暂时没有,没有。您可以将默认值存储在单独的对象中并使用 Object.assign
:
var ob = {speed: 5, distance: 8};
var defaults = {speed: 0, location: 'home'};
function f(obj) {
return Object.assign({}, defaults, obj);
}
f(ob);
是否可以通过解构设置一些默认参数,同时仍然保留默认值中未考虑的任何额外值?例如:
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}
编辑:我的函数不知道可能作为附加项传入的键的名称。例如:该函数不知道它是 receiving/returning 一个名为 'distance' 的键还是一个名为 'foo' 的键。所以我在考虑某种使用...rest 然后...spread。
您不能使用当前的 es6,但您可以使用通过第 2 阶段预设提供的 rest 运算符。
function f({speed= 0, location: 'home', ...others}) {
return Object.assign({}, {speed, location}, others);
}
Is it possible to set some default parameters via destructuring while still retaining any extra values not accounted for in the default?
暂时没有,没有。您可以将默认值存储在单独的对象中并使用 Object.assign
:
var ob = {speed: 5, distance: 8};
var defaults = {speed: 0, location: 'home'};
function f(obj) {
return Object.assign({}, defaults, obj);
}
f(ob);