默认功能参数不符合我的预期

时间:2019-09-08 16:37:12

标签: javascript node.js function parameters

我有这个功能:

const func = (a, b, options = { opt1: false, opt2: false, opt3: false }) => {
 // do something
 console.log(options); // { opt1: false, opt2: false, opt3: false }
}

所以当我在没有任何参数的情况下调用它时,我会得到这个

func('a', 'b', { opt3: true });
// { opt3: true }

而不是预期的:

// { opt1: false, opt2: false, opt3: true }

3 个答案:

答案 0 :(得分:4)

您已默认options,但您没有 默认 in 选项的各种属性。由于您要为options提供对象,因此该对象正在使用。

您可以使用解构为属性提供默认值,然后为参数提供空白默认值:

const func = (a, b, { opt1 = false, opt2 = false, opt3 = false } = {}) => {
 // do something
 console.log(opt1, opt2, opt3);
};

func(1, 2, {opt1: true});
func(1, 2);

当然,您最终将选项作为离散变量而不是对象。您随时可以重新构造对象:

const func = (a, b, { opt1 = false, opt2 = false, opt3 = false } = {}) => {
 const options = {opt1, opt2, opt3};
 // do something
 console.log(options);
};

func(1, 2, {opt1: true});
func(1, 2);

当然,由于这是您自己的对象,因此您可以根据需要为它分配其他属性,而不必担心修改调用者的对象。

如果您不想使用解构,则只需像我们在ES2015之前那样分别提供默认值,但可以使用属性扩展而不是Object.assign

const func = (a, b, options = {}) => {
 // do something
 options = {opt1: false, opt2: false, opt3: false, ...options };
 console.log(options);
};

func(1, 2, {opt1: true});
func(1, 2);

答案 1 :(得分:0)

这是正确的行为。 options = { opt1: false, opt2: false, opt3: false }仅在调用函数时没有提供没有对象。

const func = (a, b, options = { opt1: false, opt2: false, opt3: false }) => {
  // do something
  options.opt1 = options.opt1 || false
  options.opt2 = options.opt2 || false
  options.opt3 = options.opt3 || false

  console.log(options); 
 }

这是通过检查对象属性并根据是否设置它们来进行设置的方法。

答案 2 :(得分:0)

这是预期的行为。创建默认的options参数时,默认值为3个字段。通过{opt3: true}时,由于要提供自己的默认值,因此您将跳过默认值。默认值不会为您填写缺少的值。