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'
这两种判断的区别在于它们处理未定义变量的方式。
-
typeof element.children !== 'undefined':
- 这种方式首先使用
typeof
操作符来检查element.children
的类型。如果element.children
未定义,typeof element.children
返回的结果是'undefined'
,否则返回实际的数据类型。 - 因此,
typeof element.children !== 'undefined'
确保了element.children
已经被定义,并且它的类型不是'undefined'
。这是一种比较严谨的方式来检查变量是否已经被定义。
- 这种方式首先使用
-
element.children !== 'undefined':
- 这种方式直接比较
element.children
和'undefined'
。如果element.children
是未定义的,将会直接与'undefined'
进行比较。 - 这种方式在
element.children
未定义时会返回true
,因为未定义的变量与'undefined'
是相等的。但是在element.children
被定义为其他值时,可能会出现意外的结果。
- 这种方式直接比较
总的来说,typeof element.children !== 'undefined'
更加严谨,因为它首先检查变量的类型,然后再与 'undefined'
进行比较,确保变量已经被定义且不是 'undefined'
。这样可以避免一些潜在的问题,特别是在处理对象属性时。