2013-07-03 2 views
5
<script type="text/javascript"> 
function saveName (firstName) { 
    function capitalizeName() { 
     return firstName.toUpperCase(); 
    } 
    var capitalized = capitalizeName();console.log(capitalized instanceof String); 
    return capitalized; 
} 
console.log(saveName("Robert")); // Returns "ROBERT" 
</script> 

질문 :자바 스크립트 변수 유형을 확인하는 가장 좋은 방법은 무엇입니까

내가 대문자의 유형을 확인하려면, 그래서 capitalized instanceof String를 사용할 수 있습니까? 하지만, 콘솔에 false이 표시됩니다. 시도하고 싶지 않습니다. capitalized instanceof Function, Object ... 너무 오래 걸리므로 변수 유형을 감지하는 가장 좋은 방법은 무엇입니까?

+1

문자열 리터럴이'String' 유형의 객체가 아니기 때문에. 'typeof capitalized' – zerkms

답변

13

가장 좋은 방법은 typeof 키워드를 사용하는 것입니다. "string", "number", "object", "function", "undefined""boolean" :

typeof "hello" // "string" 

typeof 연산자 여섯 개 값 중 하나에 피연산자를 매핑한다. instanceof 메소드는 제공된 함수의 프로토 타입이 객체의 프로토 타입 체인에 있는지 테스트합니다.

This Wikibooks articlethis MDN articles은 JavaScript 유형을 합산하는 데 매우 효과적입니다.

+0

'typeof new String ("hello") == "object"를 참조하십시오. 그러나'string'의 모든 동일한 특성으로부터 이익을 얻을 수 있습니다. 'typeof x == "string"||라고하는 것이 가장 안전합니다. x instance of String' –

+0

실제로는 새로운 문자열 ("hello")가 사용되는 것을 거의 볼 수 없지만 당신이 맞다고 가정합니다. – LandonSchropp

+0

"JavaScript에는 다섯 가지 기본 제공 유형 만 있습니다."틀 렸습니다. 몇 가지가 더 있습니다. 'typeof' 연산자는 이들을 6 가지 가능한 결과로 매핑합니다. ''boolean ''을 잊어 버렸습니다. – user123444555621

0

사용 typeof();

예 :,의 typeof는 "원시"유형의 수를 반환 유일하게 좋은입니다

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

유의 사항 :

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

그래서 당신은 할 수있다 부울, 객체, 문자열. 또한 instanceof를 사용하여 객체가 특정 유형인지 테스트 할 수 있습니다.

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

var obj = new MyObj(10); 

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

를 대문자로.

var getType = (function() { 

    var objToString = ({}).toString , 
     typeMap  = {}, 
     types = [ 
      "Boolean", 
      "Number", 
      "String",     
      "Function", 
      "Array", 
      "Date", 
      "RegExp", 
      "Object", 
      "Error" 
     ]; 

    for (var i = 0; i < types.length ; i++){ 
     typeMap[ "[object " + types[i] + "]" ] = types[i].toLowerCase(); 
    };  

    return function(obj){ 
     if (obj == null) { 
      return String(obj); 
     } 
     // Support: Safari <= 5.1 (functionish RegExp) 
     return typeof obj === "object" || typeof obj === "function" ? 
      typeMap[ objToString.call(obj) ] || "object" : 
      typeof obj; 
    } 
}()); 

당신은 getType("Hello")

0

로 호출 할 수 있습니다 getVarType 방법 (아래) 거의 모든 변수에 대해 작동합니다. Check out this fiddle. 결과가 신뢰할만한 경우 먼저 유형을 사용합니다. 다른 경우에는 더 비싼 toString 방법을 사용합니다. 마지막으로, document.location과 같은 객체에 대해 Firefox가 반환 한 명명 된 객체를 처리하는 경우 Array와 유사한 객체를 확인하고 배열로보고합니다.

이와 대조적으로, 유형은 당황 스럽다. typeof ([])는 'object'를 반환하고, typeof (new Number())는 object를 반환합니다. 또한 실제 목적이 아닌 많은 다른 변수에 대해 '객체'를 반환합니다. 비교를 위해 바이올린 결과를보십시오.

// Begin public utility /getVarType/ 
    // Returns 'Function', 'Object', 'Array', 
    // 'String', 'Number', 'Null', 'Boolean', or 'Undefined' 
    // 
    getVarType = (function() { 
    var typeof_map = { 
     'undefined' : 'Undefined', 
     'boolean' : 'Boolean', 
     'number' : 'Number', 
     'string' : 'String', 
     'function' : 'Function', 

     'Undefined' : 'Undefined', 
     'Null'  : 'Null', 
     'Boolean' : 'Boolean', 
     'Number' : 'Number', 
     'String' : 'String', 
     'Function' : 'Function', 
     'Array'  : 'Array', 
     'StyleSheetList' : 'Array' 
    }; 

    return function(data) { 
     var type, type_str; 

     if (data === null  ) { return 'Null'; } 
     if (data === undefined) { return 'Undefined'; } 

     type  = typeof(data); 
     type_str = typeof_map[ type ]; 

     if (type_str) { return type_str; } 

     type = {}.toString.call(data).slice(8, -1); 
     return typeof_map[ type ] 
     || (data instanceof Array ? 'Array' : 
     (data.propertyIsEnumerable(0) && data.length !== undefined 
      ? 'Array' : 'Object') 
     ); 
    }; 
    }()); 
    // End public utility /getVarType/ 

비어있는 이름이 지정된 어레이를 테스트하는 경우에만 가능한 실패 모드가 발생합니다 (예 :StyleSheetList 이외의 빈 상태 (empty)의 열거 가능한 DOM 오브젝트) 그러나 on은 필요에 따라 type_of_map에 추가 할 수 있습니다.

도움이 되었기를 바랍니다.

0

변수의 자바 스크립트 유형은 typeof/instanceOf으로 결정할 수 있습니다.

하지만 어떻게 때문에, 배열과 객체를 구별하는 방법 :

typeof [] === typeof {} 

쉽게 우리가 toString 거기 클래스 이름으로 구별 할 수 있습니다

function what(v) { 
    if (v === null) return 'null'; 
    if (v !== Object(v)) return typeof v; 
    return ({}).toString.call(v).slice(8, -1).toLowerCase(); 
} 

이 나를 what 기능을 테스트하자

what({}); // 'object' 
what({abc: 123}); // 'object' 

what([]); // 'array' 
what([123, 'abc']); // 'array' 

what(function() {}); // 'function' 
what(setTimeout); // 'function' 

what(/^what\.js$/); // 'regexp' 

what(new Date()); // 'date' 

what(null); // 'null' 
what(undefined); // 'undefined' 

what('abc'); // 'string' 
what(123); // 'number' 
what(12.3); // 'number' 

what(true); // 'boolean' 
what(false); // 'boolean' 

기능 what은 단일 변수의 유형, 복잡한 변수를 검사하는 방법을 검사하기위한 것입니다.

이 사례를 처리하기 위해 what()에 대한 기본 작업을 수행했으며, 사용하기 쉬운 variable-type이라는 오픈 소스 프로젝트를 사용하여 시도해 볼 수 있습니다.

관련 문제