JavaScript for Loop 循环指南完整版

2,721 阅读5分钟

Image by Max Duzij

花几分钟重温、关于JavaScript循环指南的基础,记住一张图

在前端开发过程中,我们经常使用到JavaScript 提供了很多种循环和迭代的方法,常见for, for…of, for…in, while, Array.forEach, 以及 Array.* (还有一些 Array 方法类似于循环/迭代器: Array.values(), Array.keys(), Array.map(), Array.reducer()等),而这些都是很基础的东西,那肯定有人觉得这些都是很基础的东西,有什么的好看头的呢?整理出来的这些东西,目的为了有个框架化、脑图化。所以简单了制作了一副JS循环的脑图。把凌乱的、碎片化的知识整合在一切,更加容易记住基础

JS循环

Simple Loop

for

只要满足特定条件,for 循环就会一直重复执行。它通常用于执行代码块一定次数。

数组循环

const arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i])
}

break 语句

使用 break 语句来终止循环

for (let i = 0; ; i++) {
  console.log('loop')
  break
}

// output: loop

在这种情况下,for 循环中,break 关键字会在遇到循环时退出循环。

continue 语句

continue 语句可以用来继续执行(跳过代码块的剩余部分并进入下一个循环)

for (let i = 0; i < 3; i++) {
  if (i === 2) continue
  console.log(i)
}

// output: 0, 1

以上代码可以输入的结果来,当条件 i === 2 成立时,遇到continue 关键字跳过并进行下个循环。

for…of

for...of 语句在可迭代对象(包括 Array、Map、Set、arguments 等等)上创建了一个循环,对值的每一个独特属性调用一次迭代。

string 字符串循环

let string = 'text'

for (let value of string) {
  console.log(value) // output "t", "e", "x", "t"
}

array 数组循环

let arr = [0, 1, 2]
for (let value of arr) {
  console.log(value) // output 0, 1, 2
}

objects 对象循环

for…of 循环仅适用于可迭代的值,对象不是可迭代的,所以直接使用 for…of 来循环对象是不可行的。以下例子:

let object = { a: 1, b: 2, c: 3 }

for (let value of object) // Error: object is not iterable
  console.log(value)

可以使用内置的 Object 方法将对象转换为可迭代对象:.keys().values().entries(),看以下例子:

let enumerable = { property : 1, method : () => {} };

for (let key of Object.keys( enumerable )) console.log(key);
> property
> method

for (let value of Object.values( enumerable )) console.log(value);
> 1
> () => {}

for (let entry of Object.entries( enumerable )) console.log(entry);
> (2) ["prop", 1]
> (2) ["meth", ƒ()]

也可以通过使用 for…in 循环而不使用内置的 Object 方法来实现。

for…in

for…in 循环是一种特殊的循环类型,它遍历对象的属性或数组的元素。遍历对象时,可显示可枚举的对象属性

let object = { a: 1, b: 2, c: 3, method: () => {} }

for (let value in object) {
  console.log(value, object[value])
}

// output: 1, 2, 3, () => { }

while

一个 while 语句只要指定的条件求值为真(true)就会一直执行它的语句块。

let c = 0

while (c++ < 5) {
  console.log(c)
}

// output: 1, 2, 3, 4, 5

do…while

与 while 非常相似, 而 do...while 语句一直重复直到指定的条件求值得到假值(false)。

var i = 1
do {
  console.log(i)
  i++
} while (i <= 5)

// output: 1, 2, 3, 4, 5

Arrays Loops

Array 有多种迭代方法。通常我们建议使用内置的 Array 方法进行循环操作,而不使用 for 或 while 循环。数组方法附加到 Array.prototype 属性上,这意味着直接从数组对象使用。 例如使用Array.forEach()的方法进行操作数组

forEach

定义:forEach 方法对数组的每个元素执行一次给定的函数。 返回值: none

let arr = ['jack', 'tom', 'vincent']

arr.forEach((name) => console.log(`My name is ${name}`))

//output
// My name is jack
// My name is tom
// My name is vincent

every

定义:检测数组所有元素是否都符合判断条件,全部符合返回true, 否则false 返回值: boolean

const isBelowThreshold = (currentValue = currentValue < 40)
const array1 = [1, 30, 39, 29, 10, 13]

console.log(array1.every(isBelowThreshold))

// output: true

some

定义:数组中是否有满足判断条件的元素。至少有一个满足判断条件就会返回true,都没有满足则返回false 返回值: boolean

filter

定义:对数组的每个元素执行一次给定的函数,返回新数组 返回值:新数组

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

map

定义:方法创建一个新数组,其结果是该数组中的每个元素都调用一次提供的函数后的返回值。 返回值:新数组

const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

reduce && reduceRight

定义:reduce方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

定义:reduceRight方法接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]

find()& findIndex()

定义:find方法用于找出第一个符合条件的数组成员,并返回该成员,如果没有符合条件的成员,则返回undefined。

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

定义:findIndex返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

参考文献