【问题标题】:In Javascript is checking for the type only using typeof operator bad?在 Javascript 中仅使用 typeof 运算符检查类型不好?
【发布时间】:2011-08-16 23:38:46
【问题描述】:

我发现有很多不同的方法可以在 Javascript 中检查 var 的类型。

但是使用 typeof 运算符似乎比其他方式简单得多 - 例如

if(typeof someVar == typeof "")

if(typeof someVar == typeof [])


function myFunc() {}

if(typeof someVar == typeof myFunc)

这样做是有效的还是非常糟糕的做法?为什么?

谢谢。

【问题讨论】:

    标签: javascript types typeof


    【解决方案1】:

    typeof 非常好用,但不适用于一般类型检查。这不是它的目的。

    typeof [] == "object"
    

    它只能区分"object""function""undefined"和基元"boolean""number""string"。对于更高级的类型检查,您需要使用instanceof 或更复杂的检查。

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

    【讨论】:

    • 如果您有多个窗口对象(例如在 i/frames 中),instanceof Array 测试将不起作用。那就是window.frames[0].Array == That is window.frames[1].Array返回false
    • @JuanMendes:哎呀!我是想说这个,但我的帖子里似乎漏掉了几句话。编辑。
    【解决方案2】:

    typeof 的主要问题之一是,如果您使用它们的构造函数创建这些对象,它不会返回“string”、“boolean”、“number”。看看这个测试字符串的例子

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

    因此,在测试参数或变量是否为字符串、布尔值、数字时,需要使用返回一致结果的 Object.prototype.toString

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

    【讨论】:

      【解决方案3】:

      如果需要检查值和类型是否相同,可以使用===比较运算符;但是,如果您只需要检查类型,则最适合使用instanceof

      【讨论】:

      • 虽然我同意你的观点,但这并不意味着 w3schools 上的所有内容都不准确。它可以是有用的资源,就像 StackOverflow 一样。
      • 大多数网络开发人员不同意你的观点,诺曼,可能那里有一些准确的信息,但你为什么要继续引用一个描述草率且示例延续不良编码风格的网站。
      • 触摸。没用过,第一次参考,以后一定会参考更好的资源:)
      猜你喜欢
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      • 2022-07-14
      • 2013-10-24
      • 2018-12-08
      • 2021-09-27
      相关资源
      最近更新 更多