【问题标题】:How to check if x is an Object but not a String Object如何检查 x 是否是对象而不是字符串对象
【发布时间】:2016-09-05 16:18:52
【问题描述】:

到目前为止我所拥有的。

const isNotNullObject = function (x) {
    return (typeof x === "object" && x !== null);
};

它适用于数组和对象。但对于 String 对象也是如此!

isNotNullObject(String(5))
false
isNotNullObject(new String(5))
true

我想要的对于任何类型的字符串都是错误的。请注意,我无法控制调用代码。我自己无法删除new。出于性能原因,我需要一个不创建新字符串的解决方案,以检查是否相等。

【问题讨论】:

  • 为什么不typeof x == "object" && typeof x != "string"
  • @ifvictr 刚刚说了什么!
  • 但是字符串对象对象。像这样对待它们并假设您的调用者知道不包装字符串。
  • @ifvictr: 如果typeof x == "object"true,那么我们已经知道typeof x != "string" 也是truetypeof x 的值在第一次比较后不会改变。
  • 字符串对象是对象 - 是的,规范的噱头。

标签: javascript


【解决方案1】:

使用instance of

return (typeof x === "object" && !(x instanceof String) && x !== null)

const isNotNullObject = function(x) {
  return (typeof x === "object" && !(x instanceof String) && x !== null);
};

console.log(
  isNotNullObject(String(5)),
  isNotNullObject(new String(5))
)

【讨论】:

【解决方案2】:

有很多方法可以检查 Object/String/Array 的类型。

  • 使用type of X 运算符使用

  • Object.prototype.toString.apply(X)

    //它的性能最差

  • Object.getPrototypeOf(X)

  • X.constructor.

其中 X 可以是 Object/Array/String/Number 或任何东西。性能比较请看下图

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 2021-02-28
    • 2021-11-20
    • 2011-08-15
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多