[英]what is the best way to check variable type in javascript
<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
in console, I don't want to try capitalized instanceof Function
, Object
...这会花费太多时间,那么检测变量类型的最佳方法是什么?
最好的方法是使用typeof
关键字。
typeof "hello" // "string"
typeof
运算符将操作数映射到六个值之一: "string"
、 "number"
、 "object"
、 "function"
、 "undefined"
和"boolean"
。 instanceof
方法测试所提供函数的原型是否在对象的原型链中。
这篇 Wikibooks 文章和这篇 MDN 文章很好地总结了 JavaScript 的类型。
使用typeof();
例子:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
所以你可以这样做:
if(typeof bar === 'string') {
//whatever
}
请记住,typeof 仅适用于返回“原始”类型、数字、布尔值、对象、字符串。 您还可以使用 instanceof 来测试对象是否属于特定类型。
function MyObj(prop) {
this.prop = prop;
}
var obj = new MyObj(10);
console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
typeof 大写 == 'string'
最好的方法是使用typeof
typeof "blahha"
我在 jQuery 库代码的帮助下做了一个函数, jQuery 库类型方法 github link 。
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")
getVarType方法(如下)适用于几乎所有变量。 看看这个小提琴。 它首先采用了非常快的typeof对于其中结果是可靠的情况下。 然后它在其他情况下使用更昂贵的toString方法。 最后,如果它正在处理一个命名对象(如 Firefox 为 document.location 之类的对象返回的),它会检查类似 Array 的对象并将它们报告为数组。
相比之下, typeof差的很尴尬。 typeof([]) 返回“对象”,typeof(new Number()) 返回对象。 它还为许多其他不是(出于实际目的)对象的变量返回“对象”。 请参阅小提琴结果进行比较。
// 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 之外的一个空的可枚举 DOM 对象),则会发生唯一可能的失败模式。 但是可以根据需要将它们添加到 type_of_map 中。
我希望这有帮助!
BigInt
和Symbol
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-06-09
* @modified
*
* @description js data type checker
* @augments
* @example
* @link
*
*/
const dataTypeChecker = (data, debug = false) => {
const log = console.log;
let result = ``;
const typeString = Object.prototype.toString.call(data);
result = typeString.replace(/\[object /gi, ``).replace(/\]/gi, ``);
if(debug) {
log(`true type`, result)
}
return result;
};
export default dataTypeChecker;
export {
dataTypeChecker,
};
测试
const dataTypeChecker = (data, debug = false) => { const log = console.log; let result = ``; const typeString = Object.prototype.toString.call(data); // const typeString = Object.prototype.toString.apply(data); result = typeString.replace(/\\[object /gi, ``).replace(/\\]/gi, ``); if(!debug) { log(`true type`, result) } return result; }; const obj = {}; const func = () => {}; dataTypeChecker(NaN) //"[object Number]" dataTypeChecker(undefined) //"[object Undefined]" dataTypeChecker(true) //"[object Boolean]" dataTypeChecker({}) //"[object Object]" dataTypeChecker(func) //"[object Function]" dataTypeChecker(obj) //"[object Object]" dataTypeChecker(Symbol()) //"[object Symbol]" dataTypeChecker(null) //"[object Null]" dataTypeChecker(123) //"[object Number]" dataTypeChecker(BigInt(1n)) //"[object BigInt]" // true type Number // true type Undefined // true type Boolean // true type Object // true type Function // true type Object // true type Symbol // true type Null // true type Number // true type BigInt
2021+ 一个班轮答案。
我最喜欢的方式是不使用typeof
为什么? 因为它不提供布尔值、字符串、数字和函数以外的真实类型。
然后呢? 这是使用 Object.prototype 的小实用函数🤩
var trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
结果:
trueTypeOf([]); // array
trueTypeOf({}); // object
trueTypeOf(''); // string
trueTypeOf(new Date()); // date
trueTypeOf(1); // number
trueTypeOf(function () {}); // function
trueTypeOf(/test/i); // regexp
trueTypeOf(true); // boolean
trueTypeOf(null); // null
trueTypeOf(); // undefined
//-- difference constructor & typeof --// const fx = () => {} const arr = [] const obj = {} console.log( fx.constructor == Function ) // true console.log( arr.constructor == Array ) // true console.log( arr.constructor == Object ) // false console.log( obj.constructor == Object ) // true console.log( obj.constructor == Array ) // false console.log( typeof obj ) // object console.log( typeof arr ) // object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.