JS 中判斷數據類型是否為 null、undefined 或 NaN


判斷 undefined

var aaa = undefined; 
console.log(typeof(aaa) === "undefined"); // true

判斷 null

var aaa = null; 
console.log(!aaa && typeof(aaa)!='undefined' && aaa!=0); // true

判斷 NaN

var aaa = 0/0;
console.log(isNaN(aaa));  // true

因為 NaN 是 JavaScript 之中唯一不等於自身的值,所以可以如下判斷:

var aaa = 0/0;
console.log(aaa !== aaa);  // true

其他數據類型判斷

var a = "abcdef";
var b = 12345;
var c= [1,2,3];
var d = new Date();
var e = function(){ console.log(111); }; 


console.log(Object.prototype.toString.call(a)); // -------> [object String];
console.log(Object.prototype.toString.call(b)); //  -------> [object Number];
console.log(Object.prototype.toString.call(c)); //  -------> [object Array];
console.log(Object.prototype.toString.call(d)); //  -------> [object Date];
console.log(Object.prototype.toString.call(e)); //  -------> [object Function]; 

更多請參考:https://www.cnblogs.com/cckui/p/7524585.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM