我有如下 JavaScript 方法,
function showMsg(id) {
id = id! = null && id != undefined ? id : '';
//doing some task
}
这个 showMsg(id)
是从不同的事件调用的,id 有一些值,但 onLoad
事件不需要任何参数,所以我调用这个方法如下Onload
事件
function onLoading(){
showMsg(null);
}
这会导致任何问题吗?目前它的行为正常。但我仍然想知道在调用以 null
作为参数的方法时可能遇到的问题。
任何建议帮助都必须受到赞赏。
最佳答案
Can I use null as parameter in method calling?
简短的回答是是,您可以使用null
作为函数的参数,因为它是JS原始值之一。
文档:
您可以在 JavaScript null Reference 中看到它:
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values.
从文档中您可以看到:
In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.
换句话说,它可以替换任何其他预期的对象,特别是函数参数。
注意:
虽然您可以将 null
作为函数参数传递,但您必须避免调用 方法
或访问 的
对象,它将抛出一个 属性
nullUncaught ReferenceError
。
关于javascript - 我可以在方法调用中使用 null 作为参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447855/