Heim  >  Artikel  >  Web-Frontend  >  Js检查变量类型的代码()_javascript技巧

Js检查变量类型的代码()_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:23:551016Durchsuche

JavaScript检查变量的类型,并判断是整形或是字符串或是其它类型等等。


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

2、toString 本来是用来做字符串转换的,不过现在流行用来做变量类型的检查了。舜子这里也写了一个函数,方便检查变量的类型,可以用来代替 typeof
复制代码 代码如下:

function getType(o) {
var _t; return ((_t = typeof(o)) == "object" ? o==null && "null" || Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase();
}


执行结果:

getType("abc"); //string
getType(true); //boolean
getType(123); //number
getType([]); //array
getType({}); //object
getType(function(){}); //function
getType(new Date); //date
getType(new RegExp); //regexp
getType(Math); //math
getType(null); //null
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn