JS · 判断数据类型:null、undefined、NaN、[]、{}、数组

判断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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值