【问题标题】:Can I use null as parameter in method calling?我可以在方法调用中使用 null 作为参数吗?
【发布时间】:2017-04-17 08:26:39
【问题描述】:

我有如下 JavaScript 方法,

function showMsg(id) {
  id = id! = null && id != undefined ? id : '';
  //doing some task
}

这个showMsg(id) 被不同的事件调用,id 有一些值,但onLoad 事件不需要任何参数,所以我在Onload 事件上调用这个方法,如下所示

function onLoading(){
    showMsg(null);
}

它会引起任何问题吗?目前它的行为是正确的。但我仍然想知道在以null 为参数调用方法时可能遇到的问题。

必须感谢任何建议帮助。

【问题讨论】:

  • 直到您检查了null 的参数,它可以拥有它。
  • id=id!= null&& id!= undefined ? id: ''; 短 id=id||"";
  • 你用的是 es6 吗?然后,您可以为变量 id 设置默认值
  • 同样你检查一下,showMsg(null); 之间没有区别和 showMsg();但是,如果您的代码被其他人使用,我会保留 null 以表明该参数没有被遗忘

标签: javascript methods parameters null


【解决方案1】:

我可以在方法调用中使用null作为参数吗?

简短的回答是YES,您可以使用null 作为函数的参数,因为它是JS 原始值之一。

文档:

你可以在JavaScript null Reference看到它:

值 null 表示有意不存在任何对象值。它是 JavaScript 的原始值之一。

您可以从文档中看到:

在 API 中,通常在可以预期对象但没有相关对象的地方检索 null。

换句话说,它可以替换任何其他预期对象,特别是函数参数。

注意:

虽然您可以将null 作为函数参数传递,但您必须避免调用method 或访问null 对象的property,否则会抛出Uncaught ReferenceError

【讨论】:

  • 非常感谢您的帮助
【解决方案2】:

在 JavaScript 中,函数的参数默认为 undefined,但是 如果需要,可以在 JS 函数中将 null 作为参数传递。

【讨论】:

    【解决方案3】:

    您可以在函数定义中检查 null。 Javascript 函数本质上是可变的。因此,您可以选择不带任何参数调用它。您需要做的就是检查 id 在函数内部是否未定义。一种方法是:

        function showMsg(id){
         if(!id) { //This would check for both null and undefined values
    
         }else {
           //logic when id is some valid value
         }
        }
    
       You should add any other checks per your requirements. This is just to mention that you don't even need to bother to pass any parameter.
    

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 1970-01-01
      • 2015-12-01
      • 2013-04-13
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多