使用null检查传递的参数 - JavaScript

Kei*_*ons 5 javascript parameters function typeof

举一个示例函数:

function a(b){
    console.log(b != null ? 1 : 2);
}
Run Code Online (Sandbox Code Playgroud)

该代码工作正常,如果传递参数则打印1,如果不传递,则打印2.

但是,JSLint给了我一个警告,告诉我改为使用严格的等式,即!==.无论是否传递参数,该功能在使用时都会打印1 !==.

所以我的问题是,检查参数是否已通过的最佳方法是什么?我不想使用arguments.length,或者实际上根本不使用该arguments对象.

我试过用这个:

function a(b){
    console.log(typeof(b) !== "undefined" ? 1 : 2);
}
Run Code Online (Sandbox Code Playgroud)

^似乎工作,但它是最好的方法?

jfr*_*d00 5

当没有传递参数时,bis undefined, not null。因此,测试参数b是否存在的正确方法是:

function a(b){
    console.log(b !== undefined ? 1 : 2);
}
Run Code Online (Sandbox Code Playgroud)

!==建议使用==or !=,因为 null 和 undefined 可以强制为相等,但使用!==or===不会进行类型强制,因此您可以严格判断它是否相等undefined

  • 为了完整起见,可以去掉函数内部的`typeof`,因为我们在函数作用域内,这里不能覆盖`undefined` :) 在全局作用域中,使用`typeof(foo) 更安全) !== "未定义"`。 (2认同)