programing

Javascript 변수 유형을 얻는 더 좋은 방법?

randomtip 2022. 10. 23. 12:41
반응형

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(/./)

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

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

또는 ES7(향후 개선되는 경우 코멘트)

const { toString } = Object.prototype;

function typeOf(obj) {
  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
typeOf(async function() {}) //asyncfunction

에러, 약속, 발전기 함수를 통지해 주셔서 @johnrees님 감사합니다.

상당히 좋은 타입 캡처 기능은 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');
};

javascript에 의해 하지만, javascript를 할 수 .TYPES주의:typeof HTMLElementCollection Safari는 Safari에서 합니다.function type( Collection은 type(HTMLEment Collection)을 반환합니다.object

또한 ipr101에서 약간의 예를 변경할 수 있습니다.

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

라고 부르다

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

1행 함수:

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

이것은 과 같은 결과를 낳는다.

은 가능합니다.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를 한 모든 정상적으로 하면 IE를 . 다른 창에서 가져온 변수에서 호출하면 그냥 뱉습니다.[object Object].

의 2인치! 정말로, 내가 이 문제를 제기하는 이유 중 하나는, 긴 답변 목록에도 불구하고, 조금 더 많은 유형의 솔루션을 제공하고, 그것을 더 많은 것을 포함하도록 확장하는 방법에 대해 나중에 피드백을 얻기 위해서이다.

앞에서 설명한 바와 같이 다음 솔루션과 함께 jQuery 정의 객체의 값을 반환하는 수정사항을 포함했습니다.네이티브 오브젝트 프로토타입에 메서드를 추가합니다.나는 그것이 다른 그러한 확장을 방해할 수 있기 때문에 종종 금기시 된다는 것을 알지만, 나는 그것을 맡긴다.이 방법이 마음에 들지 않으면 기본 함수를 원하는 위치에 복사하고 모든 변수를 바꿉니다.this인수 파라미터(arguments[0] 등)를 지정합니다.

;(function() {  //  Object.realType
    function realType(toLower) {
        var r = typeof this;
        try {
            if (window.hasOwnProperty('jQuery') && this.constructor && this.constructor == jQuery) r = 'jQuery';
            else r = this.constructor && this.constructor.name ? this.constructor.name : Object.prototype.toString.call(this).slice(8, -1);
        }
        catch(e) { if (this['toString']) r = this.toString().slice(8, -1); }
        return !toLower ? r : r.toLowerCase();
    }
    Object['defineProperty'] && !Object.prototype.hasOwnProperty('realType')
        ? Object.defineProperty(Object.prototype, 'realType', { value: realType }) : Object.prototype['realType'] = realType;
})();

이렇게 간단하게 사용할 수 있습니다.

obj.realType()  //  would return 'Object'
obj.realType(true)  //  would return 'object'

주의: 통과 가능한 인수는 1개입니다.만약의 bool은true반환은 항상 소문자로 표시됩니다.

기타 예:

true.realType();                            //  "Boolean"
var a = 4; a.realType();                    //  "Number"
$('div:first').realType();                   // "jQuery"
document.createElement('div').realType()    //  "HTMLDivElement"

오브젝트가 언제 다른 라이브러리(Moo, Proto, Yui, Dojo 등)로 작성되었는지를 정의하는 등 도움이 되는 추가사항이 있으면 언제든지 코멘트나 편집을 하여 보다 정확하고 정확하게 유지하십시오.아니면 내가 만든 곳으로 가서 알려줘cdnmin 파일에 대한 빠른 링크도 있습니다.

이 버전은 보다 완전한 버전입니다.

const typeOf = obj => {
  let type = ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1]
  if (type === 'Object') {
    const results = (/^(function|class)\s+(\w+)/).exec(obj.constructor.toString())
    type = (results && results.length > 2) ? results[2] : ''
  }
  return type.toLowerCase()
}

여기서 답변한 바와 같이 다음과 같은 결과를 얻을 수 있습니다.

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

또한 클래스 또는 함수에서 작성하는 모든 인스턴스 또는 객체의 유형을 가져올 수 있습니다. (다른 응답 간에는 유효하지 않습니다.모든 응답은 객체를 반환합니다.)

class C {
  constructor() {
    this.a = 1
  }
}

function F() {
  this.b = 'Foad'
}

typeOf(new C()) // -> c
typeOf(new F()) // -> f
function getType(obj) {
    if(obj && obj.constructor && obj.constructor.name) {
        return obj.constructor.name;
    }
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

제 예비 테스트에서는 이게 꽤 잘 작동하고 있어요.첫 번째 케이스는 "new"로 작성된 객체의 이름을 인쇄하고 두 번째 케이스는 다른 모든 것을 인쇄합니다.

사용하고 있다(8, -1)왜냐하면 그 결과는 항상 '그것'에서 시작된다고 생각하기 때문이다.[object으로 끝나다]하지만 모든 시나리오에서 그게 사실인지는 확실하지 않아요.

여기서 가장 보편적인 해결책은 다음을 확인하는 것이라고 생각합니다.undefined그리고.null먼저, 그럼 전화만 해constructor.name.toLowerCase().

const getType = v =>
  v === undefined
    ? 'undefined'
    : v === null
      ? 'null'
      : v.constructor.name.toLowerCase();




console.log(getType(undefined)); // 'undefined'
console.log(getType(null)); // 'null'
console.log(getType('')); // 'string'
console.log(getType([])); // 'array'
console.log(getType({})); // 'object'
console.log(getType(new Set())); // `set'
console.log(getType(Promise.resolve())); // `promise'
console.log(getType(new Map())); // `map'

이 기능을 만들었습니다.

(다른 글로벌 이름과 충돌하지 않도록 이름을 더 고유하게 지정해야 합니다.)

function type(theThing) {
    return Object.prototype.toString.call(theThing).match(/\s([\w]+)/)[1].toLowerCase()
}
type({})           //-> 'object'
type([])           //-> 'array'
type(function(){}) //-> 'function'
    
type(null)         //-> 'null'
type(undefined)    //-> 'undefined
type(true)         //-> 'boolean'
type('hello')      //-> 'string'
type(42)           //-> 'number'

type(Symbol())     //-> 'symbol'
type(/abc/)        //-> 'regexp'
type(new Set())    //-> 'set'
// etc ...

PS: 위의 F.NiX는 클래스 또는 컨스트럭터 함수로 만든 커스텀 객체의 이름도 알려주는 보다 견고한 버전을 만들었습니다.

https://npmjs.com/package/advanced-type

저는 이 목적을 위해 패키지를 만들었습니다.

typeofcondition은 변수 유형을 체크하기 위해 사용됩니다. if-time 조건의 변수 유형을 체크하는 경우, 예를 들어 다음과 같습니다.

if(typeof Varaible_Name "undefined")
{

}

언급URL : https://stackoverflow.com/questions/7390426/better-way-to-get-type-of-a-javascript-variable

반응형