导航
×
   ❮   
HTML CSS JavaScript PHP Go ECMS

JavaScript 教程

JS 简介 JS 如何使用 JS 输出 JS 语法 JS 语句 JS 注释 JS 变量 JS 运算符 JS 条件语句 JS 循环 JS 字符串 JS 数字 JS 函数 JS 对象 JS 日期 JS 数组 JS 类型化数组 JS 集合 JS Map 映射 JS Math JS 正则表达式 JS 数据类型 JS 错误 JS 事件 JS 编程 JS 关键字参考 JS 保留关键字参考 JS 运算符参考 JS 运算符优先级 JS UTF-8 字符 JS UTF-8 符号 JS UTF-8 表情符号 JS 版本

JavaScript if 语句


JavaScript 的 if 语句

使用 JavaScript 的 if 语句,当条件为真时,执行一段代码块。

语法

if (condition) {
  //  如果条件为真,则要执行的代码块
}

请注意,if 是小写字母。大写字母(If 或 IF)会导致 JavaScript 错误。

示例

如果时间在18:00之前,请说"Good day":

if (hour< 18) {
    greeting = "Good day";
 }

The result of greeting will be:

亲自试一试 »

示例

let age = 18;
let text = "You can Not drive";

if (age >= 18) {
  text = "You can drive");
}
亲自试一试 »
let age = 16;
let text = "You can Not drive";

if (age >= 18) {
  text = "You can drive");
}
亲自试一试 »

嵌套 if

您可以在一个 if 语句中嵌套另一个 if 语句:

示例

let age = 16;
let country = "USA";
let text = "You can Not drive!";

if (country == "USA") {
  if (age >= 16) {
    text = "You can drive!";
  }
}
亲自试一试 »

嵌套的 if 语句会使你的代码更复杂。

更好的解决方案是使用逻辑 AND 运算符。

示例

let age = 16;
let country = "USA";
let text = "You can Not drive!";

if (country == "USA" && age >= 16) {
  text = "You can drive!";
}
亲自试一试 »

freew3c.com 中文网是独立运营的中文开发者学习平台,与 freew3c.com 无关联。提供的内容仅用于学习和测试,不保证内容的正确性。


Copyright @2020-2026 京ICP备888888号-8