TypeScript if else
摘要:在本教程中,你将了解 TypeScript if...else 语句。
TypeScript if 语句
if 语句根据条件执行语句。 如果条件为真,if 语句将执行其体内的语句:
if(condition) {
// if-statement
}
例如,以下语句说明了如何使用 if 语句来增加计数器变量(如果其值小于 max 常量的值):
const max = 100;
let counter = 0;
if (counter < max) {
counter++;
}
console.log(counter); // 1
输出:
1
在此示例中,由于变量 counter 从零开始,因此它小于常量 max。 表达式 counter < max 的计算结果为 true,因此 if 语句执行 counter++ 语句。
让我们将变量 counter 初始化为 100:
const max = 100;
let counter = 100;
if (counter < max) {
counter++;
}
console.log(counter); // 100
输出:
100
在此示例中,表达式 counter < max 的计算结果为 false。 if 语句不执行 counter++ 语句。 因此,输出为 100。
TypeScript if...else 语句
如果要在 if 语句中的条件计算结果为 false 时执行其他语句,可以使用 if...else 语句:
if(condition) {
// if-statements
} else {
// else statements;
}
下面展示了使用 if..else 语句的示例:
const max = 100;
let counter = 100;
if (counter < max) {
counter++;
} else {
counter = 1;
}
console.log(counter);
输出:
1
在此示例中,表达式 counter < max 的计算结果为 false,因此执行 else 分支中的语句将 counter 变量重置为 1。
三元运算符 ?:
在实践中,如果有一个简单的条件语句,可以使用三元运算符 ?: 而不是 if...else 语句来使代码更短,如下所示:
const max = 100;
let counter = 100;
counter < max ? counter++ : counter = 1;
console.log(counter);
TypeScript if...else if...else 语句
当你想要根据多个条件执行代码时,可以使用 if...else if...else 语句。
if...else if...else 语句可以有一个或多个 else if 分支,但只能有一个 else 分支。
例如:
let discount: number;
let itemCount = 11;
if (itemCount > 0 && itemCount <= 5) {
discount = 5; // 5% discount
} else if (itemCount > 5 && itemCount <= 10) {
discount = 10; // 10% discount
} else {
discount = 15; // 15%
}
console.log(`You got ${discount}% discount. `)
输出:
0
此示例使用 if...elseif...else 语句根据商品数量确定折扣。
如果商品数量少于或等于5,折扣为 5%。 执行 if 分支中的语句。
如果商品数量小于或等于 10 件,折扣为 10%。 else if 分支中的语句执行。
当商品数量大于 10 件时,折扣为 15%。 执行 else 分支中的语句。
在此示例中,假设项目数始终大于零。 但是,如果商品数量小于 0 或大于 10,则折扣为 15%。
为了使代码更健壮,可以使用另一个 else if 代替 else 分支,如下所示:
let discount: number;
let itemCount = 11;
if (itemCount > 0 && itemCount <= 5) {
discount = 5; // 5% discount
} else if (itemCount > 5 && itemCount <= 10) {
discount = 10; // 10% discount
} else if (discount > 10) {
discount = 15; // 15%
} else {
throw new Error('The number of items cannot be negative!');
}
console.log(`You got ${discount}% discount. `)
在此示例中,仅当商品数量大于 10 时,折扣为 15%。 执行第二个 else if 分支中的语句。
如果项目数小于零,则执行 else 分支中的语句。
概括
- 使用
if语句根据条件执行代码。 - 如果要在条件为
false时执行代码,请使用else分支。 最好使用三元运算符?:而不是简单的if...else语句。 - 使用
if else if...else语句根据多个条件执行代码。