javascript 如何准确获取 typeof 是 object/array/null ..?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13466803/
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
How to get exactly typeof is object/array/null..?
提问by 3gwebtrain
var obj = {},ar = [],nothing=null,empty=undefined,word ='string',headorTail = true;
console.log(typeof obj) //object
console.log(typeof ar)//object
console.log(typeof nothing)//object
console.log(typeof empty)//undefined
console.log(typeof word)//string
console.log(typeof headorTail)//boolean
But how can i get the type of obj,ar,nothing as "object, array,null"
- what is the best way to achieve this?
但是我怎样才能获得 obj,ar,nothing as 的类型"object, array,null"
- 实现这一目标的最佳方法是什么?
采纳答案by Pragnesh Chauhan
If you use jQuery, you can use jQuery.type
:
如果您使用 jQuery,则可以使用jQuery.type
:
jQuery.type(true) === "boolean"
jQuery.type(3) === "number"
jQuery.type("test") === "string"
jQuery.type(function(){}) === "function"
jQuery.type([]) === "array"
jQuery.type(new Date()) === "date"
jQuery.type(/test/) === "regexp"
Everything else returns "object"
as its type.
其他一切都"object"
作为其类型返回。
回答by Damask
You can try to extract constructor name, and you don't need JQuery:
您可以尝试提取构造函数名称,并且不需要JQuery:
function safeConstructorGet(obj) {
try {
console.log(obj.constructor.name) //object
} catch (e) {
console.log(obj)
}
}
safeConstructorGet(obj); //Object
safeConstructorGet(ar); //Array
safeConstructorGet(nothing); //null
safeConstructorGet(empty); //undefined
safeConstructorGet(word); //String
safeConstructorGet(headorTail); //Boolean
回答by Reuben Morais
function getType(obj) {
// Object.toString returns something like "[object Type]"
var objectName = Object.prototype.toString.call(obj);
// Match the "Type" part in the first capture group
var match = /\[object (\w+)\]/.exec(objectName);
return match[1].toLowerCase();
}
// Test it!
var arr = [null, undefined, {}, [], 42, "abc"];
arr.forEach(function(e){ console.log(getType(e)); });
See the Object.toStringon MDN.
请参阅MDN 上的Object.toString。
回答by 3gwebtrain
Even this too good!
连这也太好了!
function getType(v) {
return (v === null) ? 'null' : (v instanceof Array) ? 'array' : typeof v;
}
var myArr = [1,2,3];
var myNull = null;
var myUndefined;
var myBool = false;
var myObj = {};
var myNum = 0;
var myStr = 'hi';