programing

JS 객체의 타입을 확인하는 가장 정확한 방법은?

iphone6s 2023. 10. 29. 19:06
반응형

JS 객체의 타입을 확인하는 가장 정확한 방법은?

typeof연산자는 물체의 실제 형태를 찾는데 도움이 되지 않습니다.

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

Object.prototype.toString.apply(t)  

질문:.

이것이 물체의 종류를 확인하는 가장 정확한 방법입니까?

자바스크립트 사양은 객체의 클래스를 결정하는 하나의 적절한 방법을 제공합니다.

Object.prototype.toString.call(t);

http://bonsaiden.github.io/JavaScript-Garden/ #유형

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

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

check js type performance

사용하다typeof몇 가지 기본적인 문제(문자열, 숫자, 부울...)를 풀고 사용합니다.Object.prototype.toString복잡한 것(예: 배열, 날짜, RegExp)을 해결합니다.

이것이 제 해결책입니다.

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

개체의 실제 유형(원본 개체 또는 DataType 이름(String, Date, Number, ... 등)과 개체의 실제 유형(사용자 지정 개체도 포함)을 찾는 가장 좋은 방법은 개체 프로토타입의 생성자의 이름 속성을 잡는 것입니다.

네이티브 유형 Ex1:

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

표시:

String

Ex2:

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

비용이 저렴하고 간단합니다.

가장 좋은 해결책은toString(위에 명시된 바와 같이):

function getRealObjectType(obj: {}): string {
    return Object.prototype.toString.call(obj).match(/\[\w+ (\w+)\]/)[1].toLowerCase();
}

enter image description here

정당한 경고: toString고려하다, 고려.NaN a number따라서 나중에 수동으로 보호해야 합니다.Number.isNaN(value).

제안된 다른 해결책은,Object.getPrototypeOf 실패로 돌아가다null그리고.undefined

Using constructor

위의 정답에서 영감을 얻은 작은 유형의 체크 유틸리티를 정리했습니다.

thetypeof = function(name) {
        let obj = {};
        obj.object = 'object Object'
        obj.array = 'object Array'
        obj.string = 'object String'
        obj.boolean = 'object Boolean'
        obj.number = 'object Number'
        obj.type = Object.prototype.toString.call(name).slice(1, -1)
        obj.name = Object.prototype.toString.call(name).slice(8, -1)
        obj.is = (ofType) => {
            ofType = ofType.toLowerCase();
            return (obj.type === obj[ofType])? true: false
        }
        obj.isnt = (ofType) => {
            ofType = ofType.toLowerCase();
            return (obj.type !== obj[ofType])? true: false
        }
        obj.error = (ofType) => {
            throw new TypeError(`The type of ${name} is ${obj.name}: `
            +`it should be of type ${ofType}`)
        }
        return obj;
    };

예:

if (thetypeof(prop).isnt('String')) thetypeof(prop).error('String')
if (thetypeof(prop).is('Number')) // do something

언급URL : https://stackoverflow.com/questions/7893776/the-most-accurate-way-to-check-js-objects-type

반응형