로 호출 할 수 있습니다 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에 추가 할 수 있습니다.
도움이 되었기를 바랍니다.
문자열 리터럴이'String' 유형의 객체가 아니기 때문에. 'typeof capitalized' – zerkms