【发布时间】:2010-12-16 00:19:46
【问题描述】:
在 Java 中,您可以对变量使用 instanceOf 或 getClass() 来找出其类型。
如何在 JavaScript 中找出非强类型变量的类型?
例如,我如何知道bar 是Boolean 还是Number,还是String?
function foo(bar) {
// what do I do here?
}
【问题讨论】:
标签: javascript
在 Java 中,您可以对变量使用 instanceOf 或 getClass() 来找出其类型。
如何在 JavaScript 中找出非强类型变量的类型?
例如,我如何知道bar 是Boolean 还是Number,还是String?
function foo(bar) {
// what do I do here?
}
【问题讨论】:
标签: javascript
使用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';
【讨论】:
Number(1), Boolean(true)... 没有问题 唯一的问题是当您使用new 并创建了一个装箱对象时,将它们用作函数实际上对于从其他类型转换很有用。 Boolean(0) === false, Number(true) === 1
null 呢? typeof null 是“对象”
在 Javascript 中,您可以使用 typeof 函数来做到这一点
console.log(typeof bar);
【讨论】:
typeof 是运算符而不是函数。
比其他答案更精确一点 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';
}
}
【讨论】:
我对@987654321@ 如此有限感到沮丧。这是一个改进的版本:
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 中添加的。
【讨论】:
getTypeName 函数,它将正常工作。示例:let a = 42; getTypeName(a) // "Number"
getClass() 和 instanceof 对 value 起作用,而不管它是用什么类型声明的。例如,对于Object foo = "hello";,调用foo.getClass() 将产生Class<java.lang.String>。调用foo instanceof String 同样会产生true。
在 JavaScript 中,一切都是对象
console.log(type of({})) //Object
console.log(type of([])) //Object
要获得 Real 类型,请使用此
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
希望对你有帮助
【讨论】:
许多人建议使用 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
【讨论】:
您也可以将它用作项目中的 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 Project
现在您可以在 Sys.js 文件中导入此 Sys 代码。 那么你可以使用这个 Sys 对象函数来找出 JavaScript 对象的类型
您还可以检查对象是否已定义或类型是否为函数或对象是否为空...等。
var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);
console.log(Sys.isDefined(jQuery));
【讨论】:
这是一个有用的解决方案:
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
【讨论】: