如果缺少函数参数如何失败

How to fail if missing a function parameter

创建函数时,我检查是否填写了所需的参数,如下所示。

问题

这并不是一个好方法,因为它所做的只是为缺少的参数分配一个默认值。我宁愿让执行停止并告诉我哪个函数缺少参数。如果可能的话,这是怎么做到的?

func({
  system: "test1",
  type: "test2",
  summary: "test3",
  description: "test4",
});

function func (c) {
  c = c || {};
  c.system = c.system || "Missing system";
  c.type = c.type || 'Missing type';
  c.summary = c.summary || 'Missing summary';
  c.description = c.description || 'Missing description';

  console.log(c);
  console.log(c.system);
  console.log(c.type);
  console.log(c.summary);
  console.log(c.description);
};

如果找不到值则抛出错误。

if(!c.system) throw new Error("Missing system"); // This would fail if c.system is falsy

// In this case can be used:

if(!c.hasOwnProperty("system")) throw new Error("Missing system")

可以创建一个函数来检查这个。

function Check(objt, key, messageError){
    if(!objt.hasOwnProperty(key)) throw new Error(messageError)
}
Check(c, "system", "Missing system");