【问题标题】:Javascript Type ComparisonJavascript 类型比较
【发布时间】:2014-05-04 20:34:27
【问题描述】:

比较相同 javascript 类型的两个变量的最佳方法是什么?:

I.E.

[] = ['1','2','3']
[] != {}
Number = Number
null = null

等等。等等

【问题讨论】:

    标签: javascript typeof


    【解决方案1】:

    如果只是比较类型,人们会认为typeof 是正确的工具

    typeof [] === typeof ['1','2','3']; // true, both are arrays
    

    注意null、数组等都是'object'类型,也就是说

    typeof [] === typeof null; // is true (both are objects)
    typeof [] === typeof {};   // is true (both are objects)
    

    这是预期的行为。

    如果您必须专门检查 null、数组或其他内容,您可以编写一个更好的 typeof 函数

    var toType = function(obj) {
      return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
    }
    

    FIDDLE

    那你就可以了

    toType([]) === toType(['1','2','3']); // true
    toType([]) === toType({});     // false
    toType(1) === toType(9999);    // true
    toType(null) === toType(null); // true
    toType(null) === toType([]);   // false
    

    【讨论】:

    • 爱它!正是我正在寻找的 - 这是我测试中的一个随机想法。那么函数 test(){} toType(new test());哪个会显示为对象?
    • 是的,但是:function test1(){} && test2(){} 将彼此相等 toType(new test1()) == toType(new test2()); - 我真的不需要这个,只是好奇 - 其实不用担心,哈哈,我很好。感谢您的帮助!
    • 是的,它们都是object 类型,所以它们与toType() 相同。你不能真正比较对象,因为两个对象永远不会相同,即使{} == {} 也会是错误的,因为两个对象永远不会相等,即使它们包含相同的东西。
    【解决方案2】:

    如果您想区分对象“类型”,最好比较它们的原型:

    Object.getPrototypeOf([]) === Object.getPrototypeOf([1, 2, 3])
    Object.getPrototypeOf({}) !== Object.getPrototypeOf([])
    

    但是,如果您不传入对象,则会抛出此错误,因此如果您还想比较原始值的类型(包括 null),则必须进行更复杂的测试:

    function sameType(a, b) {
        var objectA = Object(a) === a,
            objectB = Object(b) === b;
        if (objectA && objectB)
            return Object.getPrototypeOf(a) === Object.getPrototypeOf(b);
        else if (!objectA && !objectB)
            return typeof a === typeof b;
        else
            return false;
    }
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        这应该适用于所有“类型”:

        function haveSameType(a,b) {
          return (a instanceof Array && b instanceof Array) ||
            (a === null && b === null) ||
            (typeof a === typeof b && 
             b !== null && 
             a !== null &&
             ! (a instanceof Array) &&
             ! (b instanceof Array)
            );
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-16
          • 1970-01-01
          • 2012-09-14
          • 2010-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-27
          相关资源
          最近更新 更多