js 判断对象和数组是否为空

一、判断对象是否为空

       方法1.  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非空

   方法 2.  let obj1 = {}

              if(JSON.stringify(obj1) == "{}"){

                    console.log("空对象")

               }else {

                  console.log("非空对象")

             }

转自 :https://www.cnblogs.com/crackedlove/p/10039939.html

 

二、判断数组是否为空

             方法1. let arr = [];

                        if (arr.length == 0){

                                   console.log("数组为空")

                         }else {

                                console.log("数组不为空")

                        }

            方法2.data = [];

                      if(data == false){

                             console.log("数组为空")

                    }

在数组直接与布尔类型比较的时候,默认都是将数组和布尔类型都转化为Number类型比较,空数组转化为Number类型的时候为0

 

转自 :https://blog.csdn.net/tangxiujiang/article/details/78634028

 

posted @ 2020-08-04 09:55  颂先生  阅读(5289)  评论(0编辑  收藏  举报