循环数组的时候报错TypeError: Cannot read properties of undefined (reading ‘forEach‘)

gridForm (gItem) {
        var this_ = this
        gItem.forEach(element => {
          this_.$set(element, 'check', false)
          if (element.children !== null) {
            this_.gridForm(element.children)
          } else {
            console.log(2)
            element.children = []
          }
        })
        console.log(gItem,'gItem.forEach')
        return gItem
      }

在执行到 if (element.children !== null)的时候就会报错 Cannot read properties of undefined (reading 'forEach')。

解决方式:在进行if (element.children !== null)判断的时候加上typeof element.children !== 'undefined'

//修改后代码
 gridForm(gItem) {
        var this_ = this
        gItem.forEach(element => {
            this_.$set(element, 'check', false)
            if (element.children !== null && typeof element.children !== 'undefined') {
                this_.gridForm(element.children)
            } else {
                console.log('2')
                this_.$set(element, 'children', []) // 使用 $set 为 element 添加 children 属性
            }
        })
        return gItem
      }

总结:

在JavaScript中,typeof 是一个操作符,用于检测给定变量的数据类型。当使用 typeof element.children !== 'undefined' 这个表达式时,它的含义是检查变量 element.children 的类型是否不是 'undefined',即判断 element.children 是否被定义。

在JavaScript中,如果一个变量没有被赋值,它的默认值就是 undefined。因此,在这种情况下,typeof element.children !== 'undefined' 的作用是确保 element.children 已经被定义,避免在尝试访问未定义的属性时出现错误。

注意:需要使用typeof element.children !== 'undefined' 而不是element.children !== 'undefined'

因为

在JavaScript中,typeof element.children !== 'undefined' 和 element.children !== 'undefined' 这两种判断的区别在于它们处理未定义变量的方式。

  1. typeof element.children !== 'undefined'

    • 这种方式首先使用 typeof 操作符来检查 element.children 的类型。如果 element.children 未定义,typeof element.children 返回的结果是 'undefined',否则返回实际的数据类型。
    • 因此,typeof element.children !== 'undefined' 确保了 element.children 已经被定义,并且它的类型不是 'undefined'。这是一种比较严谨的方式来检查变量是否已经被定义。
  2. element.children !== 'undefined'

    • 这种方式直接比较 element.children 和 'undefined'。如果 element.children 是未定义的,将会直接与 'undefined' 进行比较。
    • 这种方式在 element.children 未定义时会返回 true,因为未定义的变量与 'undefined' 是相等的。但是在 element.children 被定义为其他值时,可能会出现意外的结果。

总的来说,typeof element.children !== 'undefined' 更加严谨,因为它首先检查变量的类型,然后再与 'undefined' 进行比较,确保变量已经被定义且不是 'undefined'。这样可以避免一些潜在的问题,特别是在处理对象属性时。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值