JS判断方法
判断undefined:
var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("undefined");
}
说明:typeof 返回的是字符串,有六种可能:
“number”、“string”、“boolean”、“object”、“function”、“undefined”
判断null:
var str = null;
if(str === null){
alert("is null");
}
var tmp = null;
if (!tmp && typeof(tmp)!="undefined" && tmp!=0){
alert("null");
}
判断NaN:
var tmp = 0/0;
if(isNaN(tmp)){
alert("NaN");
}
说明:如果把 NaN 与任何值(包括其自身)相比得到的结果均是 false,所以要判断某个值是否是 NaN,不能使用 == 或 === 运算符。
提示:isNaN() 函数通常用于检测 parseFloat() 和 parseInt() 的结果,以判断它们表示的是否是合法的数字。当然也可以用 isNaN() 函数来检测算数错误,比如用 0 作除数的情况。
判断undefined和null:
var tmp = undefined;
if (tmp== undefined)
{
alert("null or undefined");
}
var tmp = undefined;
if (tmp== null)
{
alert("null or undefined");
}
说明:null==undefined
同时判断 null、undefined、数值0、false
// var str = undefined; // is null
// var str = null;
// var str = '';
// var str = 0;
// var str = false;
// var str = []; //not null
// var str = {}; // not null
if (!str) {
console.log("is null")
}else{
console.log("not null")
}
判断空数组[]
方法一: arr.length
let arr = [];
if (arr.length == 0){
console.log("数组为空")
}else {
console.log("数组不为空")
}
方法二:
JSON.stringify(arr) === '[]'
判断对象是否为空
方法一:
let obj1 = {}
let obj2 = {a:1}
function empty(obj){
for (let key in obj){
return false; //非空
}
return true; //为空
}
console.log(empty(obj1)) //true为空
console.log(empty(obj2)) //false非空
方法二:
let obj1 = {}
if(JSON.stringify(obj1) == "{}"){
console.log("空对象")
}else {
console.log("非空对象")
}
方法三:Object.keys(obj)
返回一个给定对象自身可枚举属性组成的数组。
let obj1 = {}
if (Object.keys(obj1).length == 0){
console.log("空对象")
}else {
console.log("非空对象")
}
封装一个准确判断数据类型的函数
function getType(obj){
let type = typeof obj;
if(type != "object"){
return type;
}
return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
}
判断数据类型:数组
方法一:Array.isArray()
ECMAScript 5 新方法 。不支持老的浏览器。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Array.isArray(fruits); // 返回 true
方法二:创建自定义 isArray() 函数
假如对象原型包含单词 “Array” 则返回 true。
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
方法三:instanceof
假如对象由给定的构造器创建,则 instanceof 运算符返回 true:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array // 返回 true