JavaScript for Loop 循環指南完整版

Image by Max Duzijjavascript

花幾分鐘重溫、關於JavaScript循環指南的基礎,記住一張圖前端

在前端開發過程當中,咱們常常使用到JavaScript 提供了不少種循環和迭代的方法,常見for, for…of, for…in, while, Array.forEach, 以及 Array.* (還有一些 Array 方法相似於循環/迭代器: Array.values(), Array.keys(), Array.map(), Array.reducer()等),而這些都是很基礎的東西,那確定有人以爲這些都是很基礎的東西,有什麼的好看頭的呢?整理出來的這些東西,目的爲了有個框架化、腦圖化。因此簡單了製做了一副JS循環的腦圖。把凌亂的、碎片化的知識整合在一切,更加容易記住基礎java

JS循環

Simple Loop

for

只要知足特定條件,for 循環就會一直重複執行。它一般用於執行代碼塊必定次數。c++

數組循環數組

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

break 語句框架

使用 break 語句來終止循環ide

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

// output: loop
複製代碼

在這種狀況下,for 循環中,break 關鍵字會在遇到循環時退出循環。函數

continue 語句oop

continue 語句能夠用來繼續執行(跳過代碼塊的剩餘部分並進入下一個循環)ui

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
複製代碼

參考文獻

相關文章
相關標籤/搜索