在 JavaScript 中查找变量类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4456336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding Variable Type in JavaScript
提问by Tom Tucker
In Java, you can use instanceOf
or getClass()
on a variable to find out its type.
在 Java 中,您可以在变量上使用instanceOf
或getClass()
来找出其类型。
How do I find out a variable's type in JavaScript which isn't strongly-typed?
如何在非强类型的 JavaScript 中找出变量的类型?
For example, how do I know if the bar
is a Boolean
or a Number
, or a String
?
例如,我怎么知道bar
是 aBoolean
还是 a Number
,还是 a String
?
function foo(bar) {
// what do I do here?
}
回答by Felix Kling
Use typeof
:
使用typeof
:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
So you can do:
所以你可以这样做:
if(typeof bar === 'number') {
//whatever
}
Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):
但是,如果您使用它们的对象包装器定义这些原语(您永远不应该这样做,请尽可能使用文字)时要小心:
> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"
The type of an array is still object
. Here you really need the instanceof
operator.
数组的类型仍然是object
。在这里,您确实需要instanceof
操作员。
Update:
更新:
Another interesting way is to examine the output of 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]"
With that you would not have to distinguish between primitive values and objects.
有了它,您就不必区分原始值和对象。
回答by Juan Mendes
typeof is only good for returning the "primitive" types such as number, boolean, object, string and symbols. You can also use instanceof
to test if an object is of a specific type.
typeof 仅适用于返回“原始”类型,例如数字、布尔值、对象、字符串和符号。您还可以instanceof
用于测试对象是否属于特定类型。
function MyObj(prop) {
this.prop = prop;
}
var obj = new MyObj(10);
console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
回答by krishna singh
Using 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';
回答by wajiw
In Javascript you can do that by using the typeof function
在 Javascript 中,您可以使用 typeof 函数来做到这一点
function foo(bar){
alert(typeof(bar));
}
回答by Wes
To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):
比其他答案更精确一点(有些人可能会说迂腐):
In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)
在 JavaScript 中,变量(和属性)没有类型:值有。此外,只有 6 种类型的值:Undefined、Null、Boolean、String、Number 和 Object。(从技术上讲,还有 7 种“规范类型”,但您不能将这些类型的值存储为对象的属性或变量的值——它们仅在规范本身中使用,以定义语言的工作方式。值您可以明确操作的只有我列出的 6 种类型。)
The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.
当它想要谈论“x 的类型”时,规范使用符号“Type(x)”。这只是规范中使用的符号:它不是语言的特性。
As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:
正如其他答案所表明的那样,在实践中,您可能想知道的不仅仅是值的类型——尤其是当类型为 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';
}
}
回答by Tom S?derlund
I find it frustrating that typeof
is so limited. Here's an improved version:
我发现它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);
}
};
sample test:
样品测试:
realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"
回答by WebBrother
For builtin JS types you can use:
对于内置 JS 类型,您可以使用:
function getTypeName(val) {
return {}.toString.call(val).slice(8, -1);
}
Here we use 'toString' method from 'Object' class which works different than the same method of another types.
这里我们使用来自“Object”类的“toString”方法,它的工作方式与其他类型的相同方法不同。
Examples:
例子:
// 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"
If you need a class name you can use:
如果你需要一个类名,你可以使用:
instance.constructor.name
Examples:
例子:
({}).constructor.name // "Object"
[].constructor.name // "Array"
(new Date).constructor.name // "Date"
function MyClass() {}
let my = new MyClass();
my.constructor.name // "MyClass"
But this feature was added in ES2015.
但是这个特性是在ES2015中添加的。
回答by Tarandeep Singh
Here is the Complete solution.
这是完整的解决方案。
You can also use it as a Helper class in your Projects.
您还可以将其用作项目中的 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>
For Exportable CommonJs Module or RequireJS Module....
对于可导出的 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;
Currently in Use on a public git repo. Github Project
目前在公共 git repo 上使用。 Github 项目
Now you can import this Sys code in a Sys.js file. then you can use this Sys object functions to find out the type of JavaScript Objects
现在您可以在 Sys.js 文件中导入此 Sys 代码。那么你可以使用这个 Sys 对象函数来找出 JavaScript 对象的类型
you can also check is Object is Defined or type is Function or the Object is Empty... etc.
您还可以检查对象是否已定义或类型是否为函数或对象为空...等。
- Sys.isObject
- Sys.isArguments
- Sys.isFunction
- Sys.isString
- Sys.isArray
- Sys.isUndefined
- Sys.isDate
- Sys.isNumber
- Sys.isRegExp
- 系统对象
- 系统参数
- Sys.is函数
- Sys.isString
- Sys.isArray
- Sys.isUndefined
- 系统日期
- 系统编号
- Sys.isRegExp
For Example
例如
var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);
console.log(Sys.isDefined(jQuery));
回答by yogendra saxena
In JavaScript everything is an object
在 JavaScript 中,一切都是对象
console.log(type of({})) //Object
console.log(type of([])) //Object
To get Realtype , use this
要获得Real类型,请使用此
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
Hope this helps
希望这可以帮助