Javascript 类型比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23461253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:56:49  来源:igfitidea点击:

Javascript Type Comparison

javascripttypeof

提问by Corey

What is the best way to compare two variables for identical javascript types?:

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

I.E.

IE

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

etc. etc.

等等等等

回答by adeneo

To just compare types, one would think typeofwould be the right tool

仅比较类型,人们会认为typeof这是正确的工具

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

Note that null, arrays etc. are of type 'object', which means

请注意null,数组等属于类型'object',这意味着

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

which is expected behaviour.

这是预期的行为。

If you have to specifically check for null, arrays or other things, you could just write a better typeoffunction

如果你必须专门检查空值、数组或其他东西,你可以写一个更好的typeof函数

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

FIDDLE

小提琴

Then you could do

那么你可以做

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

回答by Bergi

If you want to distinguish object "types" from each other, it might be a good idea to compare their prototypes:

如果您想将对象“类型”彼此区分开来,比较它们的原型可能是个好主意:

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

This will however throw if you're not passing in objects, so if you also want to compare the types of primitive values (including null) you will have to do more sophisticated tests:

但是,如果您不传入对象,则会抛出此问题,因此,如果您还想比较原始值的类型(包括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;
}

回答by sabof

This should work for all "types":

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

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)
    );
}