鸿蒙语言是基于TS扩展的,所以我们可以使用undefine和null。使用到了这两个,免不了会在if判断中使用,但是我们往往可能会忽略一些特殊情况,导致带来异常。
作为一个鸿蒙初学者,记录一下遇到的这个坑。
异常情况
对于一个字符串,我们可以有以下四种方式进行声明:
a: string = ""
b: string | undefined
c: string | null = null
d: string = "1"
我们可以直接对变量 abcd使用if判断。
if (this.a) {
Logger.d(`this.a true`)
} else {
Logger.d(`this.a false`)
}
if (this.b) {
Logger.d(`this.b true`)
} else {
Logger.d(`this.b false`)
}
if (this.c) {
Logger.d("this.c true")
} else {
Logger.d("this.c false")
}
if (this.d) {
Logger.d("this.d true")
} else {
Logger.d("this.d false")
}
运行上述代码逻辑,会发现日志打印:
this.a false
this.b false
this.c false
this.d true
我们知道if判断中,undefine和null都会判断为false,非undefine和null那么会判断为true。所以当用到字符串或数字上时候,会很容易忽略掉变量a这种场景,如果字符串为空,判断也会是false。
所以实际业务中,要注意判断字符串或数字是否为undefine或null,不能单纯的使用if,这种会导致空字符串也会走到else分支,业务逻辑就乱了,除非空字符串确定要走和undefine一样的逻辑。
这种情况下,我们可以使用显示判断来判定undefine和null。
if (this.b == undefined || this.b == null) {
}
补充number的测试数据:
e: number = -1
f: number = 0
g: number = 1
h: number | undefined
i: number | null = null
// 方法
if (this.e) {
Logger.d("this.e true")
} else {
Logger.d("this.e false")
}
if (this.f) {
Logger.d("this.f true")
} else {
Logger.d("this.f false")
}
if (this.g) {
Logger.d("this.g true")
} else {
Logger.d("this.g false")
}
if (this.h) {
Logger.d("this.h true")
} else {
Logger.d("this.h false")
}
if (this.i) {
Logger.d("this.i true")
} else {
Logger.d("this.i false")
}
// 运行结果
this.e true
this.f false
this.g true
this.h false
this.i false