在Java中,您可以使用instanceOf
或getClass()
在变量上查找其类型。
如何在JavaScript中找出不是强类型的变量类型?
例如,如何知道bar
a是aBoolean
还是aNumber
或a 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更加精确:
在JavaScript中,变量(和属性)没有类型:值却没有。此外,只有6种类型的值:Undefined,Null,Boolean,String,Number和Object。(从技术上讲,还有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中添加。
在JavaScript中,一切都是对象
console.log(type of({})) //Object
console.log(type of([])) //Object
要获取实型,请使用此
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
希望这可以帮助
这是完整的解决方案。
您也可以在项目中将其用作Helper类。
"use strict";
/**
* @description Util file
* @author Tarandeep Singh
* @created 2016-08-09
*/
window.Sys = {};
Sys = {
isEmptyObject: function(val) {
return this.isObject(val) && Object.keys(val).length;
},
/** This Returns Object Type */
getType: function(val) {
return Object.prototype.toString.call(val);
},
/** This Checks and Return if Object is Defined */
isDefined: function(val) {
return val !== void 0 || typeof val !== 'undefined';
},
/** Run a Map on an Array **/
map: function(arr, fn) {
var res = [],
i = 0;
for (; i < arr.length; ++i) {
res.push(fn(arr[i], i));
}
arr = null;
return res;
},
/** Checks and Return if the prop is Objects own Property */
hasOwnProp: function(obj, val) {
return Object.prototype.hasOwnProperty.call(obj, val);
},
/** Extend properties from extending Object to initial Object */
extend: function(newObj, oldObj) {
if (this.isDefined(newObj) && this.isDefined(oldObj)) {
for (var prop in oldObj) {
if (this.hasOwnProp(oldObj, prop)) {
newObj[prop] = oldObj[prop];
}
}
return newObj;
} else {
return newObj || oldObj || {};
}
}
};
// This Method will create Multiple functions in the Sys object that can be used to test type of
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
.forEach(
function(name) {
Sys['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
}
);
<h1>Use the Helper JavaScript Methods..</h1>
<code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>
对于可导出的CommonJs模块或RequireJS模块。
"use strict";
/*** Helper Utils ***/
/**
* @description Util file :: From Vault
* @author Tarandeep Singh
* @created 2016-08-09
*/
var Sys = {};
Sys = {
isEmptyObject: function(val){
return this.isObject(val) && Object.keys(val).length;
},
/** This Returns Object Type */
getType: function(val){
return Object.prototype.toString.call(val);
},
/** This Checks and Return if Object is Defined */
isDefined: function(val){
return val !== void 0 || typeof val !== 'undefined';
},
/** Run a Map on an Array **/
map: function(arr,fn){
var res = [], i=0;
for( ; i<arr.length; ++i){
res.push(fn(arr[i], i));
}
arr = null;
return res;
},
/** Checks and Return if the prop is Objects own Property */
hasOwnProp: function(obj, val){
return Object.prototype.hasOwnProperty.call(obj, val);
},
/** Extend properties from extending Object to initial Object */
extend: function(newObj, oldObj){
if(this.isDefined(newObj) && this.isDefined(oldObj)){
for(var prop in oldObj){
if(this.hasOwnProp(oldObj, prop)){
newObj[prop] = oldObj[prop];
}
}
return newObj;
}else {
return newObj || oldObj || {};
}
}
};
/**
* This isn't Required but just makes WebStorm color Code Better :D
* */
Sys.isObject
= Sys.isArguments
= Sys.isFunction
= Sys.isString
= Sys.isArray
= Sys.isUndefined
= Sys.isDate
= Sys.isNumber
= Sys.isRegExp
= "";
/** This Method will create Multiple functions in the Sys object that can be used to test type of **/
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
.forEach(
function(name) {
Sys['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
}
);
module.exports = Sys;
目前正在公共git仓库上使用。
Github项目
现在,您可以将此Sys代码导入Sys.js文件中。那么您可以使用此Sys对象函数来找出JavaScript对象的类型
您还可以检查是“对象已定义”还是类型是“功能”或“对象为空...”等等。
- Sys.isObject
- Sys.isArguments
- 系统功能
- Sys.isString
- Sys.isArray
- Sys.isUndefined
- 系统日期
- 系统号
- Sys.isRegExp
例如
var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);
console.log(Sys.isDefined(jQuery));
文章标签:javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!