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

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에서 변수 (및 속성)에는 유형이 없습니다. 값 또한 정의되지 않은 값, Null, 부울, 문자열, 숫자 및 개체의 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]" 


답변

내장 JS 유형의 경우 다음을 사용할 수 있습니다.

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

여기서는 다른 유형의 동일한 메소드와 다르게 작동하는 ‘Object’클래스의 ‘toString’메소드를 사용합니다.

예 :

// 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"

클래스 이름이 필요한 경우 다음을 사용할 수 있습니다.

instance.constructor.name

예 :

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

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

그러나이 기능은 ES2015 에 추가되었습니다 .