【问题标题】:How to check object is a Set? [duplicate]如何检查对象是一个集合? [复制]
【发布时间】:2019-07-18 11:28:52
【问题描述】:

我正在使用Set 来处理我的任务。但是当我调试时,我得到了

mySet.has 不是函数

所以我的问题是如何检查它是否是Set。喜欢ArrayArray.isArray(obj)

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用instanceof

    let a = new Set()
    let b = [1,2]
    
    console.log(a instanceof Set)
    console.log(b instanceof Set)

    旁注:-

    您也可以使用[] instanceof Array。但是,Array.isArray 是为特定目的而创建的:避免 instanceof 出现问题。即,window1.Array != window2.array;,因此,new window1.Array() instanceof window2.Array == false。同样的逻辑也适用于 Set。只要您不弄乱多个全局环境, instanceof 就可以了。如果你这样做,b.toString() == "[object Set]" 可能会更好。感谢 @andman 指出。

    【讨论】:

      【解决方案2】:

      此检查的另一种可能性是使用Object.prototype.constructor

      let a = new Set([1,2]);
      let b = [1,2];
      
      console.log("a is a Set? " + (a.constructor === Set));
      console.log("b is a Set? " + (b.constructor === Set));

      【讨论】:

        【解决方案3】:

        也许你可以使用instanceof

        阅读更多here

        let s1 = new Set()
        let s2 = ['a','b','c']
        
        console.log(s1 instanceof Set)
        console.log(s2 instanceof Set)

        【讨论】:

          猜你喜欢
          • 2017-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-30
          • 2021-04-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多