7.JavaScript中的条件是什么?

163 阅读3分钟

在JavaScript中,条件是一个计算结果为布尔值(true​或 false​)的表达式。您可以使用条件来控制程序的流程,方法是根据条件的计算结果为​true​或​false​执行不同的代码块。

以下是如何在JavaScript中使用条件的示例:

const x = 10;

if (x > 5) {
  console.log("x is greater than 5");
} else {
  console.log("x is not greater than 5");
}

在这个例子中

  • if​语句检查​x​的值是否大于​5
  • 如果是,则执行​if​语句后面的代码块,并将消息“x大于5”打印到控制台。
  • 如果​x​不大于​5​,则执行​else​语句后面的代码块,并将消息“x is not greater than 5”打印到控制台。

您还可以通过使用​else if​语句来使用多个条件。例如:

const x = 10;

if (x > 15) {
  console.log("x is greater than 15");
} else if (x > 10) {
  console.log("x is greater than 10");
} else {
  console.log("x is not greater than 10 or 15");
}

在这个例子中

  • 第一个条件检查​x​是否大于​15​。
  • 如果是,则执行第一个if语句之后的代码块
  • 如果不是,则检查第二个条件,如果x​大于10​,则执行第二个if​ 语句之后的代码块。
  • 如果这些条件都不为true,则执行else​ 语句之后的代码块

您还可以使用三元运算符,这是编写简单if​语句的速记方式。三元运算符的语法是:

condition ? value1 : value2
  • 如果​condition​计算为​true​,则表达式返回​value1
  • 否则它返回value2

以下是如何使用三元运算符的示例:

const x = 10;
const y = x > 5 ? "x is greater than 5" : "x is not greater than 5";

console.log(y);  // prints "x is greater than 5"

在此示例中,三元运算符检查x​是否大于5​。如果是,则将字符串“x is greater than 5”分配给y​变量,如果不是,则将字符串“x is not greater than 5”分配给y​变量。

Switch-Case

在JavaScript中,​switch​语句用于根据expression的值执行不同的代码块。​switch​语句的语法是:

switch (expression) {
  case value1:
    //如果expression==value 1要执行的代码
    break;
  case value2:
    // 如果expression==value 2要执行的代码
    break;
  ...
  default:
    // 如果expression不匹配上述任何值,则执行的代码
}

以下是如何在JavaScript中使用switch语句的示例:

const x = "apple";

switch (x) {
  case "apple":
    console.log("x is an apple");
    break;
  case "banana":
    console.log("x is a banana");
    break;
  default:
    console.log("x is not an apple or a banana");
}

在这个例子中

  • switch​语句评估x的值,然后执行与​x​值匹配的第一个​case​对应的代码块,在这种情况下,​x​是"apple",因此执行​case "apple"​语句后面的代码块,并将消息"x is an apple"打印到控制台。
  • 重要的是在每个​case​代码块的末尾包含一个​break​语句,以确保执行不会继续到下一个​case​。如果省略​break​语句,则将执行所有后续​case​语句的代码,直到遇到​break​语句。
  • 如果表达式的值与任何​case​值不匹配,则执行​default​语句后面的代码块。​default​语句是可选的,可用于指定在没有​case​值与表达式匹配时执行的代码块。

您还可以使用​switch​语句通过使用​typeof​运算符根据表达式的类型执行代码。例如:

const x = 10;

switch (typeof x) {
  case "number":
    console.log("x is a number");
    break;
  case "string":
    console.log("x is a string");
    break;
  default:
    console.log("x is not a number or a string");
}

在此示例中,​switch​语句评估​x​的类型,然后执行与​x​类型匹配的第一​case​对应的代码块。在这种情况下,​x​ 是一个数字number,因此执行​case "number"​语句之后的代码块,并将消息“x is a number”打印到控制台。