简体   繁体   English

在 Javascript 中是否仅使用 typeof 运算符检查类型不好?

[英]In Javascript is checking for the type only using typeof operator bad?

I see there are a whole lot of different ways to check the typeof a var in Javascript.我看到有很多不同的方法可以检查 Javascript 中的 var 类型。

But using the typeof of operator seems pretty simpler than other ways - eg但是使用运算符的 typeof 似乎比其他方式更简单 - 例如

if(typeof someVar == typeof "")

if(typeof someVar == typeof [])


function myFunc() {}

if(typeof someVar == typeof myFunc)

Is it even valid or a really bad practice to do that?这样做是有效的还是非常糟糕的做法? Why?为什么?

Thank you.谢谢你。

typeof is perfectly fine to use, but not for general type checking. typeof非常好用,但不适用于一般类型检查。 That's not its purpose.这不是它的目的。

typeof [] == "object"

It can only distinguish between "object" , "function" , "undefined" and the primitives "boolean" , "number" and "string" .它只能区分"object""function""undefined"和原语"boolean""number""string" For more advance type checking, you need to use instanceof or more complicated checks.对于更高级的类型检查,您需要使用instanceof或更复杂的检查。

[] instanceof Array // works reliably only if there's a single frame
toString.call([]) == "[object Array]" // always works, but only with some types.

One of the main problems of typeof, is that it won't return "string", "boolean", "number" if you create those objects using their constructors. typeof 的主要问题之一是,如果您使用它们的构造函数创建这些对象,它不会返回“string”、“boolean”、“number”。 Look at this example testing for strings查看此示例测试字符串

typeof "my-string" // "string"
typeof String('my-string') // 'string'
typeof new String("my-string") // "object".

Therefore, when testing whether an argument or variable is a string, boolean, number, you need to use Object.prototype.toString which returns consistent results因此,在测试参数或变量是否为字符串 boolean, number 时,需要使用返回一致结果的 Object.prototype.toString

function isString(obj) {
   return Object.prototype.toString.call(obj) == "[object String]";
}

If you need to check if both the values and types are the same you can use the === comparison operator;如果需要检查值和类型是否相同,可以使用===比较运算符; however, if you just need to check the type it would be most appropriate to use instanceof .但是,如果您只需要检查类型,则最适合使用instanceof

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM