[英]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>
Question:问题:
I want to check the type of capitalized, so I use capitalized instanceof String
?我想检查大写的类型,所以我使用
capitalized instanceof String
? But it shows: false
in console, I do not want to try capitalized instanceof Function
, Object
...It will take too much time, so what is the best way to detect a variable type?但它显示:
false
in console, I don't want to try capitalized instanceof Function
, Object
...这会花费太多时间,那么检测变量类型的最佳方法是什么?
The best way is to use the typeof
keyword.最好的方法是使用
typeof
关键字。
typeof "hello" // "string"
The typeof
operator maps an operand to one of six values: "string"
, "number"
, "object"
, "function"
, "undefined"
and "boolean"
. typeof
运算符将操作数映射到六个值之一: "string"
、 "number"
、 "object"
、 "function"
、 "undefined"
和"boolean"
。 The instanceof
method tests if the provided function's prototype is in the object's prototype chain. instanceof
方法测试所提供函数的原型是否在对象的原型链中。
This Wikibooks article along with this MDN articles does a pretty good job of summing up JavaScript's types. 这篇 Wikibooks 文章和这篇 MDN 文章很好地总结了 JavaScript 的类型。
use typeof();
使用
typeof();
example:例子:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
So you can do:所以你可以这样做:
if(typeof bar === 'string') {
//whatever
}
Keep in mind that, typeof is only good for returning the "primitive" types, number, boolean, object, string.请记住,typeof 仅适用于返回“原始”类型、数字、布尔值、对象、字符串。 You can also use instanceof to test if an object is of a specific type.
您还可以使用 instanceof 来测试对象是否属于特定类型。
function MyObj(prop) {
this.prop = prop;
}
var obj = new MyObj(10);
console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
typeof 大写 == 'string'
The best way is using typeof
最好的方法是使用
typeof
typeof "blahha"
I made a function with help of jQuery library code, jQuery library type method github link .我在 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;
}
}());
You can call it as getType("Hello")
您可以将其称为
getType("Hello")
The getVarType method (below) works for almost all variables. getVarType方法(如下)适用于几乎所有变量。 Check out this fiddle .
看看这个小提琴。 It first uses the very fast typeof for cases where the results are reliable.
它首先采用了非常快的typeof对于其中结果是可靠的情况下。 Then it uses a more expensive toString method for other cases.
然后它在其他情况下使用更昂贵的toString方法。 Finally, if it is dealing with a named object (as returned by Firefox for objects like document.location) it checks for Array-like objects and reports them as arrays.
最后,如果它正在处理一个命名对象(如 Firefox 为 document.location 之类的对象返回的),它会检查类似 Array 的对象并将它们报告为数组。
In comparison, typeof is embarrassingly poor.相比之下, typeof差的很尴尬。 typeof([]) returns 'object', typeof(new Number()) returns object.
typeof([]) 返回“对象”,typeof(new Number()) 返回对象。 It also returns 'object' for many other variables that aren't (for practical purposes) objects.
它还为许多其他不是(出于实际目的)对象的变量返回“对象”。 See the fiddle results for a comparison.
请参阅小提琴结果进行比较。
// 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/
The only possible failure mode happens if you are testing a named array that is empty (eg an empty enumerable DOM object besides the StyleSheetList).如果您正在测试一个空的命名数组(例如,除了 StyleSheetList 之外的一个空的可枚举 DOM 对象),则会发生唯一可能的失败模式。 But on could add those to the type_of_map as needed.
但是可以根据需要将它们添加到 type_of_map 中。
I hope that helps!我希望这有帮助!
BigInt
& Symbol
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,
};
test
测试
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+ one liner answer. 2021+ 一个班轮答案。
My favourite way is not to use typeof
我最喜欢的方式是不使用
typeof
Why?为什么? because it doesn't give true type for other than boolean,string,number & function.
因为它不提供布尔值、字符串、数字和函数以外的真实类型。
Then what?然后呢? Here is small utility function using Object.prototype 🤩
这是使用 Object.prototype 的小实用函数🤩
var trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
Results:结果:
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.