参考文档 : <HarmonyOS第一课>ArkTS开发语言介绍
TypeScript 中的 if 语句 / if else 语句 用法 , 与 JavaScript 语言中的 if 语句 / if else 语句 语法 基本相同 ;
if else 语句语法如下 :
if (condition1) {
// 当 condition1 为真时执行的代码块
} else if (condition2) {
// 当 condition1 为假,但 condition2 为真时执行的代码块
} else if (condition3) {
// 当 condition1 和 condition2 都为假,但 condition3 为真时执行的代码块
} else {
// 当所有条件都为假时执行的代码块
}
condition1 / condition2 / condition3 条件会 按照顺序进行判断 ,
一旦某个条件为真 , 就会 执行相应的代码块 , 并且跳过后续的所有 else if 和 else 代码块 ;
如果 condition1 / condition2 / condition3 条件 都为 false , 则执行最后的 else 代码块 ;
if 语句 :
let age: number = 19;
if (age > 18) {
console.log("大于 18 岁成年");
}
在 https://ts.nodejs.cn/play 中运行 TypeScript 代码 :
[LOG]: "大于 18 岁成年"
if else 语句 :
let age: number = 19;
if (age > 18) {
console.log("成年了");
} else {
console.log("未成年");
}
在 https://ts.nodejs.cn/play 中运行 TypeScript 代码 :
[LOG]: "成年了"
TypeScript 语言 的 switch case 语句 语法 与 JavaScript 语言 基本相同 , 该条件语句结构可以根据 一个表达式的值 来执行不同的 case 代码块中的代码 ;
switch case 语法 :
switch (expression) {
case value1:
// 当 expression 表达式值 等于 value1 时执行该代码块
break;
case value2:
// 当 expression 表达式值 等于 value2 时执行该代码块
break;
default:
// 如果上面的 case 后的 表达式值 都不匹配 , 则执行该代码块
break;
}
代码示例 :
let color: string = "Blue";
switch (color) {
case "Blue":
console.log("蓝色");
break;
case "Red":
console.log("红色");
break;
case "Purple":
console.log("紫色");
break;
default:
console.log("未知颜色");
break;
}
在 https://ts.nodejs.cn/play 中运行 TypeScript 代码 :
[LOG]: "蓝色"