[javascript] Javascript 변수 유형을 얻는 더 좋은 방법은 무엇입니까?

JS보다 변수 유형을 얻는 더 좋은 방법이 typeof있습니까? 당신이 할 때 잘 작동합니다 :

> typeof 1
"number"
> typeof "hello"
"string"

그러나 시도 할 때 쓸모가 없습니다.

> typeof [1,2]
"object"
>r = new RegExp(/./)
/./
> typeof r
"function"

나는 알고 instanceof있지만 사전에 유형을 알아야합니다.

> [1,2] instanceof Array
true
> r instanceof RegExp
true

더 좋은 방법이 있습니까?



답변

Angus Croll은 최근 이것에 관한 흥미로운 블로그 게시물을 썼습니다.

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

그는 다양한 방법의 장단점을 살펴보고 새로운 방법 ‘toType’을 정의합니다.

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


답변

를 사용해보십시오 constructor.name.

[].constructor.name
new RegExp().constructor.name

모든 JavaScript와 마찬가지로 누군가는 결국 이것이 어떻게 든 악하다고 지적 할 것이므로 이를 잘 다루는 답변에 대한 링크가 있습니다.

대안은 사용하는 것입니다 Object.prototype.toString.call

Object.prototype.toString.call([])
Object.prototype.toString.call(/./)


답변

합리적으로 좋은 형식 캡처 기능은 YUI3에서 사용하는 것입니다 .

var TYPES = {
    'undefined'        : 'undefined',
    'number'           : 'number',
    'boolean'          : 'boolean',
    'string'           : 'string',
    '[object Function]': 'function',
    '[object RegExp]'  : 'regexp',
    '[object Array]'   : 'array',
    '[object Date]'    : 'date',
    '[object Error]'   : 'error'
},
TOSTRING = Object.prototype.toString;

function type(o) {
    return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};

이것은 자바 스크립트가 제공하는 많은 프리미티브를 캡처하지만 항상 TYPES객체 를 수정하여 더 많은 것을 추가 할 수 있습니다 . 참고 typeof HTMLElementCollection사파리보고에서 function, 그러나 유형 (HTMLElementCollection) 반환합니다object


답변

다음 기능이 유용 할 수 있습니다.

function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

또는 ES7에서 (추가 개선의 경우 의견)

function typeOf(obj) {
  const { toString } = Object.prototype;
  const stringified = obj::toString();
  const type = stringified.split(' ')[1].slice(0, -1);

  return type.toLowerCase();
}

결과 :

typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new Error) //error
typeOf(Promise.resolve()) //promise
typeOf(function *() {}) //generatorfunction
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map

오류, 약속, 생성기 함수를 알려 주신 @johnrees에게 감사드립니다.


답변

또한 우리는 ipr101 에서 작은 예제를 변경할 수 있습니다

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

로 전화

"aaa".toType(); // 'string'


답변

한 줄 기능 :

function type(obj) {
    return Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/,"$1").toLowerCase()
}

이것은 같은 결과를 제공합니다 jQuery.type()


답변

Object.prototype.toString모든 객체에 적용 할 수 있습니다 .

var toString = Object.prototype.toString;

console.log(toString.call([]));
//-> [object Array]

console.log(toString.call(/reg/g));
//-> [object RegExp]

console.log(toString.call({}));
//-> [object Object]

이것은 IE를 제외하고 모든 브라우저에서 잘 작동합니다. 다른 창에서 얻은 변수에서 이것을 호출하면 그냥 뱉어집니다 [object Object].