语句
if
最常用的条件控制语句,没有之一。
可以嵌套 else if()
和 else {}
进行流程控制。
while
当 while()
中的条件为 true
的时候,一直执行其中的函数。
do-while
与 while
很相似,但是区别在于,至少执行 do
中的指令一次,不管 while
中的条件是什么。
switch
与 if-else if-else
可互换,但是在以单一条件为判断条件的时候, switch
的语法看起来更加清晰。另外,在 单一条件 的数据量比较大的时候, switch
的表现比 if-else if-else
要稍微高效一些。
for
除了 if
之外用的最多的循环体了。
for-in
用于枚举对象中的 非符号(Symbol) 属性。
因为对象中 属性 的存储并不是按序的,所以无法保证所有属性的顺序。
const obj = {
a: "1",
b: "2",
c: "3",
d: "4",
};
for (const key in obj) {
// 分别在不同行输出 a, b, c, d
console.log(key);
}
关于 JS 中的可枚举属性,可以查看 MDN 的 这篇文档
for-of
用于迭代 可迭代对象。使用 for-of
的条件之一是:不需要关注 可迭代对象 的 index
。
const arr = [1, 2, 3, 4, 5];
for (const val of arr) {
// 分别在不同行输出 1,2,3,4,5
console.log(val);
}
之前有过 for...of
和 forEach
是否可以互换的想法,后来找了下发现: arguments
没有 forEach
函数。
大多数情况下应该都是可以互换的,例如说 Map
, Set
都有 forEach
函数,Array
, String
本身又是 Array
类,但是,的确存在个例,因此两个函数不能完全互换。
break & continue
跳出循环体 和 跳出当前循环体,进入下一个循环的区别。
标签语句
这个很有意思,我想起了大二时候的汇编课作业。
其他语言应该也会有吧,不过我在其他语言里面没碰到过 标签语句 是真的。
语法为: label: statement
。
标签语句与 continue
搭配:
var i, j;
loop1: for (i = 0; i < 3; i++) {
//The first for statement is labeled "loop1"
loop2: for (j = 0; j < 3; j++) {
//The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
continue loop1;
}
console.log("i = " + i + ", j = " + j);
}
}
// Output is:
// "i = 0, j = 0"
// "i = 0, j = 1"
// "i = 0, j = 2"
// "i = 1, j = 0"
// "i = 2, j = 0"
// "i = 2, j = 1"
// "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"
标签语句与 break
搭配:
var i, j;
loop1: for (i = 0; i < 3; i++) {
//The first for statement is labeled "loop1"
loop2: for (j = 0; j < 3; j++) {
//The second for statement is labeled "loop2"
if (i == 1 && j == 1) {
break loop1;
}
console.log("i = " + i + ", j = " + j);
}
}
// Output is:
// "i = 0, j = 0"
// "i = 0, j = 1"
// "i = 0, j = 2"
// "i = 1, j = 0"
// Notice the difference with the previous continue example
其他的应用还包括在 块级代码 中与 break
搭配使用:
foo: {
console.log("face");
break foo;
console.log("this will not be executed");
}
console.log("swap");
// this will log:
// "face"
// "swap
with
可以省略一点代码,例如说:
let qs = location.search.substring(1);
let hostName = location.hostname;
let url = location.href;
// 等同于
with (location) {
let qs = search.substring(1);
let hostName = hostname;
let url = href;
}
不过 MDN 标注了不推荐使用,其一是因为没有向前兼容,其二语义不明显,存在语义上的歧义,如:
function f(x, o) {
with (o)
// 如果存在 o.x 的属性,就会输出 o.x
// 如果不存在 o.x,将会输出 x
// 问题的关键就在于,作为开发者并不能够百分百保证传进来的参数的所有数值是否有重名
// 为了省略一个 o.x 的调用,再加一个 if 检查,就很没必要了……
print(x);
}