我想要做的是将一个对象传递给一个函数,其中可以设置某些默认值,并且整个对象应该有一个名称以将其传递给另一个函数。
下面的代码,没有命名参数,工作得很好。
function test({
item1,
item2 = 0
}) {
console.log(item1 + " " + item2);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}
但是如果我现在开始设置obj = {...}传递给print()我会得到一个语法错误:
function test(obj = {
item1,
item2 = 0
}) {
print(obj);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}
如果我写item2: 0,不会有错误,但是 inprint item2是未定义的。
从下面的答案来看,这似乎是迄今为止最适合我的方式:
function test(obj) {
obj = Object.assign({
item1: undefined,
item2: 0
}, obj);
print(obj);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}