if语句中的Javascript默认条件未执行

qq24tv8q  于 2023-02-21  发布在  Java
关注(0)|答案(3)|浏览(135)

我正在尝试编写一个if语句,如果输入已定义,则打印“input is defined”,否则打印undefined。

function isItUndefined(param) 
{
    console.log(typeof(param))
   if (typeof(param) !== undefined) 
   {
       return 'Input is defined'
   }
   return undefined
}
console.log(isItUndefined(5))
console.log(isItUndefined(null))
console.log(isItUndefined(undefined))

但是,由于即使条件为false,default语句也不会执行,因此上述代码会给出以下输出:

number
Input is defined
object
Input is defined
undefined
Input is defined
ia2d9nvy

ia2d9nvy1#

typeof返回一个string,因此您的代码应该是:

if (typeof(param) !== 'undefined') {
  // Print
}

MDN实际上有一个dedicated page,关于如何检测undefined的值,以及使用每个方法可能会遇到什么样的问题。例如,使用typeof实际上可能会导致一个bug,而使用单元测试相对容易捕捉到:如果您在param中输入错误,则if语句几乎总是true

2izufjch

2izufjch2#

typeof operator返回一个字符串,因此要么直接将输入与值undefined进行比较,要么将typeof param与字符串'undefined'进行比较。

if (typeof param !== 'undefined') 
// or
if (param !== undefined)
wpx232ag

wpx232ag3#

您不需要typeof来执行此操作

function isItUndefined(param) {
   return param === undefined ? "undefined" : "Input is defined"; 
   // If the goal is to print the return value you may prefer to return a string in both cases, in order to have a consistent return type.
}

console.log(isItUndefined(5))
console.log(isItUndefined(null))
console.log(isItUndefined(undefined))
console.log(isItUndefined())

相关问题