《鸿蒙第一行代码》第二课:学习null和undefined的区别
undefined:
是一个变量或者对象从来没被赋值过,最原始的状态
原始状态会在以下 4 种场景中出现
- 声明了一个变量,但没有赋值
- 访问对象上不存在的属性
- 函数定义了形参,但没有传递实参
- 使用 void 对表达式求值
null:
是人为赋值的,它的用处,如果你想回收某个对象,就赋值null给它
简单示例代码:
class Person {
}
@Entry
@Component
struct Null_Undefined_diff_Page {
@State message: string = 'Hello World'
person?: Person|null
aboutToAppear(){
// // 第一点的说明
// let a:number
// console.log("a1:"+a);
// // 第二点说明
// let arr = []
// console.log("arr1:"+arr[1])
// // 第三点说明
// this.test()
// // 第四点说明
// let student:Student
// console.log("st22",student?.pet?.petName)
//
// // null的情况 人为的赋值null
// let b = null
// 声明一个person,但是没有初始化
if(this.person == null) {
console.log("person is null"); // person is null
}
}
test(name?:string){
console.log("name1:"+name)
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}