数组的遍历
ES5 中数组遍历方式
let arr = [1, 2, 3, 2, 4]
ES5中数组遍历的方法
for循环
for (let i = 0; i < arr.length; i++) {
console.log(arr[i])
}
后来语法有所升级,到 ES5 遍历数组的 API 多了起来,其中有 forEach、every、filter等,同样的功能可以用 forEach 、 map 、 every 等方法来实现。
forEach() 没有返回值,只是针对每个元素调用func
arr.forEach(function(elem(值), index(索引), array(数组本身)) {
if (arr[i] == 2) {
continue
}
console.log(elem, index)
})
这个语法看起来要简洁很多,不需要通过索引去访问数组项,然而它的缺点也是很明显,不支持 break、continue 等。
[1, 2, 3, 4, 5].forEach(function(i) {
if (i === 2) {
return;
} else