高階函數替換JavaScript中的循環

JavaScript新方法代替傳統循環方法操做。本篇文章對比介紹實際場景方法運用。

爲何高階函數替換循環?javascript

使用高階函數將使您的代碼能夠使你的代碼可讀性更強,易於理解,便於調試。java

JavaScript高階函數替換循環

JavaScript高階函數替換循環數組

場景示例函數

1、遍歷數組元素,返回一個修改後的新數組。spa

e.g. 將數組元素轉換爲大寫調試

循環方式:code

const animal = ['dog', 'cat', 'monkey', 'tiger'];
let upperCaseAnimal = [];
for(const item of animal) {
  upperCaseAnimal.push(item.toUpperCase());
}
// 輸出
0: "DOG"
1: "CAT"
2: "MONKEY"
3: "TIGER"

不用循環blog

const animal = ['dog', 'cat', 'monkey', 'tiger'];
let upperCaseAnimal = animal.map(item => item.toUpperCase());

結果也是同樣。ip

2、遍歷數組元素,並執行某一方法。rem

循環:

const animal = ['dog', 'cat', 'monkey', 'tiger'];
function output(name) {
  console.log(name);
}
for (const item of animal) {
  output(item);
}

不用循環:

const animal = ['dog', 'cat', 'monkey', 'tiger'];
function output(name) {
  console.log(name);
}
animal.forEach(name=> output(name));

3、數組元素過濾。

e.g. 返回數組中的奇數。

循環:

const numbers = [1, 2, 3, 4, 5];
const odd = [];
for (const item of numbers) {
  if ( item % 2 ) {
    odd.push(item);
  }
}

不用循環:

const numbers = [1, 2, 3, 4, 5];
const odd = numbers.filter(item => item % 2);
// 輸出結果
[1, 3, 5]

4、數組元素求和。

循環:

const numbers = [1, 2, 3, 4, 5];
let result = 0;
for (const item of numbers) {
  result  = item;
}

不用循環:

const numbers = [1, 2, 3, 4, 5];
let result = numbers.reduce((acc, val) => acc + val, 0);
// 輸出結果
15

5、檢測數組中的元素是否知足指定條件。

循環:

const numbers = [1, 2, 3, 4, 5];
for (const item of numbers) {
  if (item === 3) {
    console.log('Y');
  }
}

不用循環:

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.some(item => item === 3));

補充:

some() 方法用於檢測數組中的元素是否知足指定條件(函數提供)。

some() 方法會依次執行數組的每一個元素:

若是有一個元素知足條件,則表達式返回true , 剩餘的元素不會再執行檢測。

若是沒有知足條件的元素,則返回false。

注意: some() 不會對空數組進行檢測。

注意: some() 不會改變原始數組。

6、檢查數組中每一個元素是否均知足指定條件。

循環:

const numbers = [1, 2, 3, 4, 5];
for (const item of numbers) {
  if (item > 0) {
    console.log(item);
  }
}

不用循環:

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.every(item => item > 0));

補充:

every() 方法用於檢測數組全部元素是否都符合指定條件(經過函數提供)。

every() 方法使用指定函數檢測數組中的全部元素:

若是數組中檢測到有一個元素不知足,則整個表達式返回 false ,且剩餘的元素不會再進行檢測。

若是全部元素都知足條件,則返回 true。

注意: every() 不會對空數組進行檢測。

注意: every() 不會改變原始數組。

好了,就到這裏,晚安!?

掃碼_搜索聯合傳播樣式-標準色版_gaitubao_663x242.png

相關文章
相關標籤/搜索