在 Java 中,可以对变量使用 instanceOf或 getClass()来查找其类型。
instanceOf
getClass()
如何在 JavaScript 中查找不是强类型的变量的类型?
例如,如何知道 bar是 Boolean还是 Number,或者是 String?
bar
Boolean
Number
String
function foo(bar) { // what do I do here? }
在 Javascript 中,可以通过使用 typeof 函数来实现这一点
console.log(typeof bar);
使用 typeof:
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。
object
更新:
另一个有趣的方法是检查 Object.prototype.toString的输出:
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来测试对象是否具有特定类型。
instanceof
function MyObj(prop) { this.prop = prop; } var obj = new MyObj(10); console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
使用 type:
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';
ECMAScript-5.1-比其他答案更精确一些(有些人可能会说迂腐) :
在 JavaScript 中,变量(和属性)没有类型: 值有。此外,只有6种类型的值: 未定义、空、布尔、字符串、数字和对象。(从技术上讲,也有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]"
您还可以在项目中将其用作 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>
"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.js 文件中导入这段 Sys 代码。 然后您可以使用这个 Sys 对象函数来查找 JavaScript 对象的类型
你也可以检查是 Object is Defied 或者 type is Function 或者 Object is Empty... 等等。
var m = function(){}; Sys.isObject({}); Sys.isFunction(m); Sys.isString(m); console.log(Sys.isDefined(jQuery));
在 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]
希望这个能帮上忙
对于内置的 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中添加的。
很多人建议使用 typeOf,但是忘记了 JS qwirks。 下面是您可以使用的一个班轮实用程序函数
const 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
这里有一个有用的解决方案:
newTypeOf = (value) => { return Object.prototype.toString.call(value).split(' ')[1].split(']')[0].toString() } newTypeOf(12) // Number newTypeOf('') // String newTypeOf([]) // Array newTypeOf({}) // Number newTypeOf(null) // Null newTypeOf(undefined) // Undefined newTypeOf(()=>{}) // Function