programing tip

자바 스크립트에서 변수 유형 찾기

itbloger 2020. 7. 4. 11:09
반응형

자바 스크립트에서 변수 유형 찾기


Java에서는 instanceOf또는 getClass()변수를 사용 하여 유형을 찾을 수 있습니다.

JavaScript에서 강력하게 유형이 지정되지 않은 변수 유형을 찾으려면 어떻게합니까?

예를 들어, 내가 어떻게이 경우 알 수 있습니까 barA는 Boolean또는 Number또는를 String?

function foo(bar) {
    // what do I do here?
}

사용 typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

그래서 당신은 할 수 있습니다 :

if(typeof bar === 'number') {
   //whatever
}

이 프리미티브를 객체 래퍼로 정의하는 경우주의하십시오 (가능한 경우 절대 리터럴을 사용하지 마십시오).

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

배열의 유형은 여전히 object입니다. 여기에는 실제로 instanceof연산자 가 필요합니다 .

최신 정보:

또 다른 흥미로운 방법은 다음의 출력을 검사하는 것입니다 Object.prototype.toString.

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

이를 통해 기본 값과 객체를 구분할 필요가 없습니다.


typeof는 숫자, 부울, 객체, 문자열 및 기호와 같은 "기본"유형을 반환하는 데만 적합합니다. instanceof객체가 특정 유형인지 테스트하는 데 사용할 수도 있습니다 .

function MyObj(prop) {
  this.prop = prop;
}

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true

사용 type:

// Numbers
typeof 37                === 'number';
typeof 3.14              === 'number';
typeof Math.LN2          === 'number';
typeof Infinity          === 'number';
typeof NaN               === 'number'; // Despite being "Not-A-Number"
typeof Number(1)         === 'number'; // but never use this form!

// Strings
typeof ""                === 'string';
typeof "bla"             === 'string';
typeof (typeof 1)        === 'string'; // typeof always return a string
typeof String("abc")     === 'string'; // but never use this form!

// Booleans
typeof true              === 'boolean';
typeof false             === 'boolean';
typeof Boolean(true)     === 'boolean'; // but never use this form!

// Undefined
typeof undefined         === 'undefined';
typeof blabla            === 'undefined'; // an undefined variable

// Objects
typeof {a:1}             === 'object';
typeof [1, 2, 4]         === 'object'; // use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date()        === 'object';
typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1)     === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object';  // this is confusing. Don't use!

// Functions
typeof function(){}      === 'function';
typeof Math.sin          === 'function';

Javascript에서는 typeof 함수를 사용하여 그렇게 할 수 있습니다

function foo(bar){
  alert(typeof(bar));
}

다른 답변보다 ECMAScript-5.1 정확도가 약간 더 높습니다 (일부는 pedantic이라고 할 수 있음).

JavaScript에서 변수 (및 속성)에는 유형이 없습니다. 값 또한 6 가지 유형의 값, 즉 정의되지 않음, 널, 부울, 문자열, 숫자 및 오브젝트 만 있습니다. (기술적으로는 7 개의 "사양 유형"도 있지만 객체의 속성이나 변수의 값으로 해당 유형의 값을 저장할 수 없습니다. 언어의 작동 방식을 정의하기 위해 사양 내에서만 사용됩니다. 값 내가 명시한 6 가지 유형 만 명시 적으로 조작 할 수 있습니다.)

이 스펙은 "x 유형"에 대해 이야기 할 때 "Type (x)"표기법을 사용합니다. 이것은 사양 내에서 사용 된 표기법 일 뿐이며 언어의 기능이 아닙니다.

다른 답변에서 알 수 있듯이 실제로는 특히 유형이 Object 인 경우 값의 유형보다 더 많은 것을 알고 싶을 수 있습니다. 그럼에도 불구하고 완벽 함을 위해 다음은 사양에서 사용되는 Type (x)의 간단한 JavaScript 구현입니다.

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}

나는 그것이 typeof너무 제한적 이라는 것을 알았습니다 . 개선 된 버전은 다음과 같습니다.

var realtypeof = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            if (obj instanceof Date)
                return '[object Date]';
            if (obj instanceof RegExp)
                return '[object regexp]';
            if (obj instanceof String)
                return '[object String]';
            if (obj instanceof Number)
                return '[object Number]';

            return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};

샘플 테스트 :

realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]" 

다음은 완벽한 솔루션입니다.

프로젝트에서 도우미 클래스로 사용할 수도 있습니다.

"use strict";
/**
 * @description Util file
 * @author Tarandeep Singh
 * @created 2016-08-09
 */

window.Sys = {};

Sys = {
  isEmptyObject: function(val) {
    return this.isObject(val) && Object.keys(val).length;
  },
  /** This Returns Object Type */
  getType: function(val) {
    return Object.prototype.toString.call(val);
  },
  /** This Checks and Return if Object is Defined */
  isDefined: function(val) {
    return val !== void 0 || typeof val !== 'undefined';
  },
  /** Run a Map on an Array **/
  map: function(arr, fn) {
    var res = [],
      i = 0;
    for (; i < arr.length; ++i) {
      res.push(fn(arr[i], i));
    }
    arr = null;
    return res;
  },
  /** Checks and Return if the prop is Objects own Property */
  hasOwnProp: function(obj, val) {
    return Object.prototype.hasOwnProperty.call(obj, val);
  },
  /** Extend properties from extending Object to initial Object */
  extend: function(newObj, oldObj) {
    if (this.isDefined(newObj) && this.isDefined(oldObj)) {
      for (var prop in oldObj) {
        if (this.hasOwnProp(oldObj, prop)) {
          newObj[prop] = oldObj[prop];
        }
      }
      return newObj;
    } else {
      return newObj || oldObj || {};
    }
  }
};

// This Method will create Multiple functions in the Sys object that can be used to test type of
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
.forEach(
  function(name) {
    Sys['is' + name] = function(obj) {
      return toString.call(obj) == '[object ' + name + ']';
    };
  }
);
<h1>Use the Helper JavaScript Methods..</h1>
<code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>

내보낼 수있는 CommonJs 모듈 또는 RequireJS 모듈의 경우 ...

"use strict";

/*** Helper Utils ***/

/**
 * @description Util file :: From Vault
 * @author Tarandeep Singh
 * @created 2016-08-09
 */

var Sys = {};

Sys = {
    isEmptyObject: function(val){
        return this.isObject(val) && Object.keys(val).length;
    },
    /** This Returns Object Type */
    getType: function(val){
        return Object.prototype.toString.call(val);
    },
    /** This Checks and Return if Object is Defined */
    isDefined: function(val){
        return val !== void 0 || typeof val !== 'undefined';
    },
    /** Run a Map on an Array **/
    map: function(arr,fn){
        var res = [], i=0;
        for( ; i<arr.length; ++i){
            res.push(fn(arr[i], i));
        }
        arr = null;
        return res;
    },
    /** Checks and Return if the prop is Objects own Property */
    hasOwnProp: function(obj, val){
        return Object.prototype.hasOwnProperty.call(obj, val);
    },
    /** Extend properties from extending Object to initial Object */
    extend: function(newObj, oldObj){
        if(this.isDefined(newObj) && this.isDefined(oldObj)){
            for(var prop in oldObj){
                if(this.hasOwnProp(oldObj, prop)){
                    newObj[prop] = oldObj[prop];
                }
            }
            return newObj;
        }else {
            return newObj || oldObj || {};
        }
    }
};

/**
 * This isn't Required but just makes WebStorm color Code Better :D
 * */
Sys.isObject
    = Sys.isArguments
    = Sys.isFunction
    = Sys.isString
    = Sys.isArray
    = Sys.isUndefined
    = Sys.isDate
    = Sys.isNumber
    = Sys.isRegExp
    = "";

/** This Method will create Multiple functions in the Sys object that can be used to test type of **/

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
    .forEach(
        function(name) {
            Sys['is' + name] = function(obj) {
                return toString.call(obj) == '[object ' + name + ']';
            };
        }
    );


module.exports = Sys;

현재 공개 git repo에서 사용 중입니다. Github 프로젝트

이제이 Sys 코드를 Sys.js 파일로 가져올 수 있습니다. 이 Sys 객체 함수를 사용하여 JavaScript 객체의 유형을 찾을 수 있습니다.

Object is Defined 또는 type is Function 또는 Object is Empty ... 등을 확인할 수도 있습니다.

  • Sys.isObject
  • Sys.isArguments
  • Sys.isFunction
  • Sys.isString
  • Sys.isArray
  • Sys.isUndefined
  • Sys.isDate
  • Sys.isNumber
  • Sys.isRegExp

For Example

var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);

console.log(Sys.isDefined(jQuery));

In JavaScript everything is an object

console.log(type of({}))  //Object
console.log(type of([]))  //Object

To get Real type , use this

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

Hope this helps


For builtin JS types you can use:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

If you need a class name you can use:

instance.constructor.name

Examples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

But this feature was added in ES2015.

참고URL : https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript

반응형