JavaScript 函数中的必填参数

Avatar of Chris Coyier
Chris Coyier

哇,这太聪明了!我从David 的博客中获得了灵感。

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// These will throw errors
hello();
hello(undefined);

// These will not
hello(null);
hello('David');

这里的想法是使用默认参数,就像这里 b 参数一样,如果什么都不传递,则使用默认值。

function multiply(a, b = 1) {
  return a * b;
}

因此,在上面,如果您不提供 name,它将使用默认值,即抛出错误的函数。