3

我想要做的是将一个对象传递给一个函数,其中可以设置某些默认值,并且整个对象应该有一个名称以将其传递给另一个函数。

下面的代码,没有命名参数,工作得很好。

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);
}

4

2 回答 2

2

解构从传递给函数的对象中提取属性,并将这些属性放入独立变量中——仅此而已。您要做的是改变参数之一,而不是将参数中的属性提取到独立变量中。

您不能在参数列表中改变参数 - 对于您正在寻找的那种逻辑,您必须在以下函数体内进行test

function test(obj) {
  if (!obj.hasOwnProperty('item2')) {
    obj.item2 = 0;
  }
  print(obj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj.item1 + " " + obj.item2);
}

如果您有很多要为其分配默认值的属性,则可以使用Object.assign

function test(obj) {
  const filledObj = Object.assign({
    item2: 0,
    item3: 'item3'
  }, obj);
  print(filledObj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj);
}

如果您只想将具有某些属性的对象传递给print,然后像您最初所做的那样在参数列表中提取这些属性,然后将仅具有这些属性的重构对象传递给print

function test({
  item1,
  item2 = 0
}) {
  const obj = { item1, item2 };
  print(obj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj.item1 + " " + obj.item2);
}

于 2019-03-17T07:59:02.427 回答
0

=在 javascript 中分配值无效,您正在寻找{key: value}.

更改=:以修复错误:

// You want to destructure you object, drop the `obj =`
function test({item1,item2 = 0}) {
  // If you were to modify this data, 
  // use `Object.assign({}, {item1,item2})` to prevent mutating your data
  print({item1,item2});
  
}

// save some space by destructuring the items you want
function print({item1, item2}) {
  console.log(`${item1} ${item2}`);
}

// Initial expected result
test({item1: "foo"});

对象解构与默认值

我假设您期望 的值item2等于0正确?它不等于0,因为您传入了一个新对象,该对象覆盖了函数参数中的对象。

就像你要设置一样:

function(a = 1){}

并传入一个值,a将不再相等1,因为它已被新值替换。

您在第一个代码片段(没有obj = {...})中获得预期行为的原因是因为您正在解构一个对象。这不是一项任务,而是从对象中提取所需的部分。

当您有一个带有以下参数的函数时:

function({arg1, arg2}){}

JavaScript 将从您传入的对象中提取这些键。

分配默认值

另一方面,如果你想在不解构的情况下传入一个对象,你可以这样做:

function(obj = {a: 'default'}){}

但是,如果您直接在上面的函数中传入一个对象,则该对象及其所有键(a或任何其他键)的默认值将被您传入的任何对象替换。这是一个关于默认参数如何工作的链接javascript

我强烈建议您了解解构,它在处理 javascript 中的对象或数组时非常有用。

希望这可以帮助,

于 2019-03-17T07:58:05.193 回答