typeof 和toStirng 資料型別判斷
阿新 • • 發佈:2018-12-30
typeof 返回值有六種可能: "number," "string," "boolean," "object," "function," 和 "undefined."
var a; var a1='people'.name; alert("a的型別" + typeof a);//undefined alert("a1的型別" + typeof a1);//undefined var b = false; alert("b的型別" + typeof b);//boolean var c = 'abc'; alert("c的型別" + typeof c);//string var d = 2; var d1 = 2.3; alert("d的型別" + typeof d);//number alert("d1的型別" + typeof d1);//number var e = function () { }; var e1 = function () { return 1; }; alert("e的型別" + typeof e);//function alert("e1的型別" + typeof e1);//function var f = null; var f1= [];f1[f1.length]="張三"; alert("f的型別" + typeof f);//object alert("f1的型別" + typeof f1);//object
想區別物件、陣列 單純使用 typeof 是不行的,JavaScript中,通過Object.prototype.toString方法,判斷某個物件值屬於哪種內建型別。
由於 JavaScript 中一切都是物件,任何都不例外,對所有值型別應用 Object.prototype.toString.call() 方法結果如下:
<script type="text/javascript"> console.log(typeof 123)//number console.log(typeof '123')//string console.log(typeof true)//boolean console.log(typeof function(){})//function console.log(typeof {})//object console.log(typeof [])//object console.log(typeof new Date())//object console.log(typeof null)//object console.log(typeof undefined)//undefined console.log(Object.prototype.toString.call(123)) //[object Number] console.log(Object.prototype.toString.call('123')) //[object String] console.log(Object.prototype.toString.call(true)) //[object Boolean] console.log(Object.prototype.toString.call(function(){})) //[object Function] console.log(Object.prototype.toString.call({})) //[object Object] console.log(Object.prototype.toString.call([])) //[object Array] console.log(Object.prototype.toString.call(new Date()) )//[object Date] console.log(Object.prototype.toString.call(null)) //[object Null] console.log(Object.prototype.toString.call(undefined)) //[object Undefined] </script>
判斷是否為函式
function isFunction(it) {
return Object.prototype.toString.call(it) === '[object Function]';
}
判斷是否為陣列:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}