「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战」。
1. forEach
forEach
用来遍历数组,用forEach
有以下特征:
- 相比于
for
循环,形式更加简洁 - 没有返回值
- 不能使用
break
、continue
来控制循环 - 若使用
return
,则会跳过当前循环,直接进入下一个循环,不会跳出外层函数
在forEach
中,使用break
或continue
,会直接报错:
const arr = [0, 1, 2, 3, 4, 5];
arr.forEach((item, index) => {
if (index === 2) break; // SyntaxError: Illegal break statement
console.log(item);
});
const arr = [0, 1, 2, 3, 4, 5];
arr.forEach((item, index) => {
if (index === 2) continue; // SyntaxError: Illegal continue statement
console.log(item);
});
如下代码,在index===2
的时候,希望跳出test
函数,然而实际上只是跳过了当前的循环:
const arr = [0, 1, 2, 3, 4, 5];
function test() {
arr.forEach((item, index) => {
if (index === 2) return;
console.log(item);
});
}
test();
// 0
// 1
// 3
// 4
// 5
而同样功能,使用for
循环就可以直接跳出test
函数:
const arr = [0, 1, 2, 3, 4, 5];
function test() {
const len = arr.length;
for (let i = 0; i < len; i++) {
if (i === 2) return;
console.log(arr[i]);
}
}
test();
// 0
// 1
2. for-in
for...in
语句以任意顺序遍历一个对象的除Symbol
以外的可枚举属性。
for (variable in object){
...
}
variable
:在每次迭代时,variable
会被赋值为不同的key
,即属性名。object
:非Symbol
类型的可枚举属性被迭代的对象。
for ... in
更适合遍历对象,不建议与数组一起使用,因为遍历顺序有可能不是按照实际数组的索引顺序。
for ... in
会遍历所有的可枚举属性,包括原型:
const obj = { a: 1, b: 2, c: 3 };
function myObj() {
this.name = 'Jack';
}
myObj.prototype = obj;
const user = new myObj();
for (const prop in user) {
console.log(`user.${prop} = ${user[prop]}`);
}
// user.name = Jack
// user.a = 1
// user.b = 2
// user.c = 3
如果想仅迭代自身的属性,需要使用hasOwnProperty()
方法判断某个属性是否是该对象的实例属性:
const obj = { a: 1, b: 2, c: 3 };
function myObj() {
this.name = 'Jack';
}
myObj.prototype = obj;
const user = new myObj();
for (const prop in user) {
if (user.hasOwnProperty(prop)) {
console.log(`user.${prop} = ${user[prop]}`);
}
}
// user.name = Jack
3. for-of
for...of
语句在可迭代对象(包括 Array
,Map
,Set
,String
,TypedArray
,arguments
对象等 )上创建一个迭代循环,并为每个不同属性的值执行语句。
for (variable of iterable) {
...
}
variable
:在每次迭代中,将不同属性的值分配给variable
。iterable
:被迭代枚举其属性的对象。
与
forEach()
不同的是,它可以正确响应break
、continue
和return
语句。
迭代数组:
const arr = [10, 20, 30];
for (const value of arr) {
console.log(value);
}
// 10
// 20
// 30
迭代Map
:
const map = new Map([
['a', 1],
['b', 2],
['c', 3],
]);
for (const entry of map) {
console.log(entry);
}
// ["a", 1]
// ["b", 2]
// ["c", 3]
for (const [key, value] of map) {
console.log(value);
}
// 1
// 2
// 3
迭代arguments
对象:
(function () {
for (const argument of arguments) {
console.log(argument);
}
})(1, 2, 3);
// 1
// 2
// 3
4. 总结
forEach
是数组的方法,遍历数组,没有返回值,不能使用break
、continue
,不能用return
到跳出外层函数。for...in
语句以任意顺序迭代对象的键,包括原型。不建议与数组一起使用。for...of
语句遍历可迭代对象的值。