最近在项目中遇到 Uncaught (in promise) TypeError: list is not iterable 报错,虽然不影响代码运行,但是看着报错感觉有点难受,试试能不能解决它

看了很多篇文章,都是说使用 Object.keys() 可以解决问题

formatTree2(list) {
      for (const item of Object.keys(list)) {
        if (list[item].children && list[item].children.length === 0) {
          delete list[item].children
        } else {
          this.formatTree2(list[item].children)
        }
      }
    },

就先使用 Object.keys() 看看,代码运行之后

因为 Object.keys() 传入的是 null 和 undefined 时就会出现这种问题,如何解决呢,试试加条件判断

formatTree2(list) {
      if (list) {
        for (const item of Object.keys(list)) {
          if (list[item].children && list[item].children.length === 0) {
            delete list[item].children
          } else {
            this.formatTree2(list[item].children)
          }
        }
      }
    },

添加条件判断之后,确实能够解决,代码正常运行,也不报错了,很好

仔细琢磨一下,感觉加条件判断的话是不是可以不使用 Object.keys() 呢,值得一试

formatTree2(list) {
      if (list) {
        for (const item of list) {
          if (item.children && item.children.length === 0) {
            delete item.children
          } else {
            this.formatTree2(item.children)
          }
        }
      }
    },

代码运行之后,功能正常也不报错,确实是可以的

总结一下:

使不使用 Object.keys() 其实都可以,主要的关键点在于添加条件使得 list 在不为null或undefined时执行代码,如果为了保险起见可以添加 Object.kes() ,看项目需求吧

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐