你好!欢迎来到这篇关于 JavaScript 比较和条件语句的全面回顾。掌握这些概念对于编写逻辑清晰、功能强大的代码至关重要。


nullundefined 数据类型的比较

在 JavaScript 中,nullundefined 是两种特殊的值,它们在比较行为上有所不同。

  • undefined:当你声明一个变量但没有给它赋值时,它的默认值就是 undefined。在进行数字比较时,undefined 会被转换为 NaN(非数字),而任何与 NaN 的比较(除了 ==)都会返回 false

    console.log(undefined > 0);  // false
    console.log(undefined < 0);  // false
    console.log(undefined == 0); // false
    
  • nullnull 表示一个值的有意缺失。在使用宽松相等运算符 == 时,nullundefined 被认为是相等的。然而,当你使用严格相等运算符 === 时,由于它不进行类型强制转换,nullundefined 会被视为不相等,因为它们的类型不同。

    console.log(null == undefined); // true
    console.log(null === undefined); // false
    

switch 语句

switch 语句是另一种处理多重条件分支的强大工具,它比一连串的 if/else if 语句更简洁、可读性更强。

switch 语句会评估一个表达式的值,并将其与一系列的 case 子句进行匹配。当找到匹配时,与该 case 语句关联的代码块就会被执行。每个 case 块的末尾通常应加上 break 语句,以终止执行并跳出 switch 语句。如果省略 break,代码会继续执行到下一个 case

default 子句是可选的,只有在所有 case 都不匹配时才会被执行。default 通常放在 switch 语句的末尾。

这是一个根据星期几来输出不同消息的例子:

const dayOfWeek = 3;

switch (dayOfWeek) {
  case 1:
    console.log("It's Monday! Time to start the week strong.");
    break;
  case 2:
    console.log("It's Tuesday! Keep the momentum going.");
    break;
  case 3:
    console.log("It's Wednesday! We're halfway there."); // 匹配并执行
    break;
  case 4:
    console.log("It's Thursday! Almost the weekend.");
    break;
  case 5:
    console.log("It's Friday! The weekend is near.");
    break;
  case 6:
    console.log("It's Saturday! Enjoy your weekend.");
    break;
  case 7:
    console.log("It's Sunday! Rest and recharge.");
    break;
  default:
    console.log("Invalid day! Please enter a number between 1 and 7.");
}

通过掌握这些比较规则和条件语句,你可以更精确地控制程序的逻辑流程,使代码更加健壮和易于维护。

更多推荐