[javascript] JS 객체의 유형을 확인하는 가장 정확한 방법은 무엇입니까?

typeof운영자는 정말 개체의 실제 유형을 발견하는 데 도움이되지 않습니다.

이미 다음 코드를 보았습니다.

Object.prototype.toString.apply(t)  

질문:

객체 유형을 확인 하는 가장 정확한 방법입니까?



답변

JavaScript 사양은 객체의 클래스를 결정하는 올바른 방법을 정확히 제공합니다.

Object.prototype.toString.call(t);

http://bonsaiden.github.com/JavaScript-Garden/#types


답변

Object.prototype.toString좋은 방법이지만, 성능은 최악이다.

http://jsperf.com/check-js-type

js 유형 성능 확인

사용하여 typeof몇 가지 기본적인 문제 (문자열, 숫자, 부울 …) 사용을 해결하기 위해 Object.prototype.toString(배열, 날짜, 정규식 등) 복잡한 무언가를 해결하기 위해.

그리고 이것은 내 해결책입니다.

var type = (function(global) {
    var cache = {};
    return function(obj) {
        var key;
        return obj === null ? 'null' // null
            : obj === global ? 'global' // window in browser or global in nodejs
            : (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function
            : obj.nodeType ? 'object' // DOM element
            : cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math
            || (cache[key] = key.slice(8, -1).toLowerCase()); // get XXXX from [object XXXX], and cache it
    };
}(this));

로 사용:

type(function(){}); // -> "function"
type([1, 2, 3]); // -> "array"
type(new Date()); // -> "date"
type({}); // -> "object"


답변

허용 된 답변은 정확하지만 빌드하는 대부분의 프로젝트 에서이 작은 유틸리티를 정의하고 싶습니다.

var types = {
   'get': function(prop) {
      return Object.prototype.toString.call(prop);
   },
   'null': '[object Null]',
   'object': '[object Object]',
   'array': '[object Array]',
   'string': '[object String]',
   'boolean': '[object Boolean]',
   'number': '[object Number]',
   'date': '[object Date]',
}

이런 식으로 사용 :

if(types.get(prop) == types.number) {

}

각도를 사용하는 경우 깨끗하게 주입 할 수도 있습니다.

angular.constant('types', types);


답변

var o = ...
var proto =  Object.getPrototypeOf(o);
proto === SomeThing;

객체가 가질 것으로 예상되는 프로토 타입을 처리 한 다음 비교하십시오.

예를 들어

var o = "someString";
var proto =  Object.getPrototypeOf(o);
proto === String.prototype; // true


답변

나는 여기에 표시된 대부분의 솔루션이 과도하게 엔지니어링되어 어려움을 겪고 있다고 주장합니다. 값이 유형인지 확인하는 가장 간단한 방법은 아마도 그 속성에 [object Object]대해 확인 .constructor하는 것입니다.

function isObject (a) { return a != null && a.constructor === Object; }

또는 화살표 기능으로 더 짧습니다.

const isObject = a => a != null && a.constructor === Object;

a != null하나가 전달 수 있기 때문에 일부는 필요하다 null또는 undefined당신이 중 하나에서 생성자 속성을 추출 할 수 없습니다.

다음을 통해 생성 된 모든 객체와 작동합니다.

  • Object생성자
  • 리터럴 {}

그것의 또 다른 멋진 기능은를 사용하는 사용자 정의 클래스에 대한 올바른 보고서를 제공 할 수 있다는 것입니다 Symbol.toStringTag. 예를 들면 다음과 같습니다.

class MimicObject {
  get [Symbol.toStringTag]() {
    return 'Object';
  }
}

여기서 문제 Object.prototype.toString는 인스턴스를 호출 할 때 잘못된 보고서 [object Object]가 반환된다는 것입니다.

let fakeObj = new MimicObject();
Object.prototype.toString.call(fakeObj); // -> [object Object]

그러나 생성자를 검사하면 올바른 결과가 나타납니다.

let fakeObj = new MimicObject();
fakeObj.constructor === Object; // -> false


답변

객체의 REAL 유형 (기본 객체 또는 DataType 이름 (예 : String, Date, Number, .. 등)과 객체의 REAL 유형 (사용자 정의 이름 포함)을 모두 찾는 가장 좋은 방법은 잡아내는 것입니다. 객체 프로토 타입 생성자의 이름 속성 :

기본 유형 Ex1 :

var string1 = "Test";
console.log(string1.__proto__.constructor.name);

표시합니다 :

String

예 2 :

var array1 = [];
console.log(array1.__proto__.constructor.name);

표시합니다 :

Array

커스텀 클래스 :

function CustomClass(){
  console.log("Custom Class Object Created!");
}
var custom1 = new CustomClass();

console.log(custom1.__proto__.constructor.name);

표시합니다 :

CustomClass


답변

내가 아는 오래된 질문. 변환 할 필요가 없습니다. 이 기능을 참조하십시오 :

function getType( oObj )
{
    if( typeof oObj === "object" )
    {
          return ( oObj === null )?'Null':
          // Check if it is an alien object, for example created as {world:'hello'}
          ( typeof oObj.constructor !== "function" )?'Object':
          // else return object name (string)
          oObj.constructor.name;
    }

    // Test simple types (not constructed types)
    return ( typeof oObj === "boolean")?'Boolean':
           ( typeof oObj === "number")?'Number':
           ( typeof oObj === "string")?'String':
           ( typeof oObj === "function")?'Function':false;

}; 

예 :

function MyObject() {}; // Just for example

console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() );         // Function
console.log( getType( {} ));                    // Object
console.log( getType( [] ));                    // Array
console.log( getType( new MyObject() ));        // MyObject

var bTest = false,
    uAny,  // Is undefined
    fTest  function() {};

 // Non constructed standard types
console.log( getType( bTest ));                 // Boolean
console.log( getType( 1.00 ));                  // Number
console.log( getType( 2000 ));                  // Number
console.log( getType( 'hello' ));               // String
console.log( getType( "hello" ));               // String
console.log( getType( fTest ));                 // Function
console.log( getType( uAny ));                  // false, cannot produce
                                                // a string

저렴하고 간단합니다.