• JavaScript判断是否为空对象的几种方法


    点击打开视频讲解

    <template>
      <div id="app">
        <h2>JavaScript判断是否为空对象的几种方法h2>
      <button @click="handerNullObj">1、空对象对应的字符串为 "{}"button>
      <button @click="handerForIn">2、for inbutton>
      <button @click="handerGetOwnPropertyNames">3、Object.getOwnPropertyNames()button>
      <button @click="handerKeys">4、ES6 的 Object.keys()button>
      div>
    template>
    
    <script>
    export default {
      name: 'App',
      data(){
        return {
          
        }
      },
      methods:{
        // 1、空对象对应的字符串为 "{}"
        handerNullObj(){
          let data = {};
          let b = JSON.stringify(data) == "{}";
          console.log(b); // true
        },
        // 2、for in
        handerForIn(){
          let obj = {};
          let b = function () {
            for (let key in obj) {
              return false;
            }
            return true;
          };
          console.log(b()); //true
        },
        // 3、Object.getOwnPropertyNames()
        // Object 对象的 getOwnPropertyNames 方法,获取到对象中的属性名,存到一个数组中,返回数组对象,我们可以通过判断数组的 length 来判断此对象是否为空。
        handerGetOwnPropertyNames(){
          let data = {};
          let arr = Object.getOwnPropertyNames(data);
          console.log(arr.length == 0); // true
        },
        // 4、ES6 的 Object.keys()
        // 此方法也是返回对象中属性名组成的数组。
        handerKeys(){
          let data = {};
          let arr = Object.keys(data);
          console.log(arr.length == 0); // true
        },
      }
        
    }
    script>
    
    <style scoped>
     
    style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
  • 相关阅读:
    ESB优势2019-架构师(六十二)
    SQL Server SSIS的安装
    springboot+jsp+ssm助农系统农产品宣传网站设计
    开源OCR模型对比
    requirements.txt文件如何生成及导入
    Spark SQL 概述
    Ae 效果:CC Slant
    Netty——部分优化以及搭建简单RPC框架(笔记)
    Spring学习篇(一)
    块格式化上下文 & 堆叠上下文
  • 原文地址:https://blog.csdn.net/LS_952754/article/details/126064793