这篇笔记整理了 JavaScript 中条件判断与循环最常用的几种写法,适合刚接触前端或者时不时忘语法的同学快速捡起来。涵盖 if、switch、三目运算符,以及 for、while、for...of。
一、if 条件语句
最简单的情况:用 if 检查一个值是否等于 10,这里用 ===。
const x = 10;
if (x === 10) {
console.log('x is 10');
}
运行输出:x is 10。
双等号 == 会做类型转换,所以即使 x 是字符串 "10",x == 10 也为真。换成 === 就不行了,因为类型不同。很多人习惯用 === 来避免无意的类型转换。
const x = "10";
if (x == 10) {
console.log("x is 10");
}
if-else:条件不成立时走 else。
const x = 20;
if (x === 10) {
console.log("x is 10");
} else {
console.log("x is not 10");
}
输出:x is not 10。


