當創建一個函式時,我檢查所需的引數是否填寫如下。
題
這不是一個很好的方法,因為它所做的只是為缺失的引數分配一個默認值。我寧愿讓執行停止并告訴我哪個函式缺少引數。如果可能的話,這是怎么做的?
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);
};
uj5u.com熱心網友回復:
如果找不到值則拋出錯誤。
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");
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345970.html
標籤:javascript 节点.js ecmascript-6 错误处理
上一篇:Vue.js3和搜索
下一篇:使用zsh更改json檔案中的值
