天天看點

8個常用的JavaScript數組方法每個開發人員都必須知道

8個常用的JavaScript數組方法每個開發人員都必須知道

英文 | https://javascript.plainenglish.io/array-methods-that-every-javascript-developer-must-know-3aa311e15a66

翻譯 | 楊小二

數組是程式員最常用的東西之一。在本文中,我将介紹重要的 JavaScript 數組方法,這些方法将幫助你提升工作效率,同時,也會讓你作為開發人員的生活變得更加輕松。作為示例,我将使用 student 對象的 student 數組來處理所有這些不同的數組方法。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
]      

現在,讓我們開始吧。

1、filter()

現在,我們假設,我們想要得到這個清單中年齡小于或等于 24歲的所有學生。我們需要使用filter方法來過濾掉所有大于 24 歲的學生。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 


const filteredStudents = students.filter((students) => {
  //this filter method just takes a single function, which is going to have one parameter of   student   which is every student/item in the array
  // we'd need to return a true or false statement on whether or not we want to include them in the   new array
  return students.age <= 24
  //This line basically stashes all of the students whose ages are less than a 24 in the new   filteredStudents array
})


console.log(filteredStudents)


//      

這種filter()數組方法超級好用。你所做的就是為每個項目傳回 true 或 false。如果為真,則将其添加到新數組中,如果為假,則不添加。filter 方法和本文中所有其他方法的優點在于,它們實際上不會更改你正在過濾的底層對象,是以我們可以記錄學生數組,并且它仍然包含所有項目。這非常友善,因為我們在使用這些新數組方法建立新數組時,不必擔心更改舊數組。

2、map()

map() 允許你擷取一個數組并将其轉換為一個新數組。在這個中,新數組中的所有項目看起來都略有不同。如果我們想得到每個學生的名字。我們可以通過使用 map() 擷取名稱數組。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 


const studentNames = students.map((students) => {
//the method takes a single function, with the students/items as a parameter
// here we just return what we want in the new array
return students.name
})


console.log(studentNames)


/*If we print out these student names,
console.log(studentNames)
we get a new array that is just full of all the different names of the students.*/


                                                  /******************/      

這可以通過數組中的任何内容來完成。例如,當你想要擷取一個對象,并且隻擷取名稱或單個鍵,或者擷取一個數組并将其轉換為另一個數組時,該方法非常有用。此方法是 JavaScript 數組中最流行的方法之一。

3、find()

此方法允許你在數組中查找單個對象。這是直截了當的方法。假設我們想找到一個名叫 john 的學生。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 


const singleStudent = students.find((students) => {
return students.name === 'john'
})


console.log(singleStudent)
/*
  console.log(singleStudent) will give the everything associated with john in this example, I.e
   Object {
    age: 25,
    name: "john",
    score: 86
  }


*/      

在這個方法中,邏輯是有一個 true 或 false 語句,它将傳回第一個計算結果為 true 的數組項。

4、forEach()

與其他方法不同, forEach() 實際上不傳回任何内容,是以不需要 return 語句。假設我們需要列印出 student 數組中所有學生的名字,我們會這樣做:

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 


students.forEach((students) => {
  console.log(students.name)
})


/*
  the result is the name property printed out on the console line after line like so


  "sam"
  "john"
  "dean"
  "timothy"
  "frank"
 */      

這将與 for 循環非常相似,但它将采用一個函數。是以,對于每個數組項,它将執行函數内的代碼塊。

這種方法隻是使處理需要循環項目的數組變得更加容易,因為你不必像通常那樣寫出笨重而長的for循環語句。

5、some()

這個方法與我們的大多數其他函數有點不同,它不是傳回一個全新的數組,而是傳回 true 或 false。是以我們可以檢查這個數組中是否有一些學生是未成年人。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 


const hasUnderageStudents = students.some((students) => {
   return students.age < 18
})


console.log(hasUnderageStudents)
/*
  this will return false because there is no underage student in the array.
*/      

是以,如果任何學生項目的年齡值低于 18,該函數将傳回 true。該方法隻是檢查數組中是否有任何内容傳回 true,如果是,則整個内容傳回 true。

6、every()

此方法與 some() 非常相似,除了檢查至少一項以評估為真或假之外,它會檢查以確定每一項都符合給定的條件。

如果我使用 some() 代碼示例中使用的相同代碼。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 


const hasUnderageStudents = students.every((students) => {
return students.age < 18
})


console.log(hasUnderageStudents)
// this returns false because there are no ages below 18      

如果我要将條件更改為每個項目評估為真的條件,則整個事情都會傳回真。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 
const hasUnderageStudents = students.every((students) => {
  return students.age < 40
})


console.log(hasUnderageStudents)
// this will return true because every single age property is below 40      

7、reduce()

此方法與所有其他方法完全不同,因為它實際上是對數組進行一些操作并傳回所有這些不同操作的組合。

假設我想要學生數組中所有項目的總分,通常會進行 for 循環并每次都将分數相加,在循環結束時,将列印出總分。為了避免冗長的過程,你可以使用 reduce() 方法來執行此操作。

簡化方法的文法與其他方法不同。它不是采用數組本身,而是采用一個數組和一個屬性,用于我們想要将所有内容減少到和在我們的示例中的分數。除了函數之外,它還需要第二個參數,這将是你的起點,在我們的例子中,我們希望從零開始我們的總數。

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
] 
const totalScore = students.reduce((currentTotal, students) => {
  return students.score + currentTotal
}, 0)


console.log(totalScore)      

在代碼讀取時,我們有 reduce() 方法,該方法對數組中的每一項運作一個函數。

該函數的第一個參數将是該數組的前一次疊代傳回的任何内容,第二個參數是數組中的實際項目。

currentTotal 将在第一次疊代時開始,使用我們作為 reduce() 方法的第二個參數傳入的任何内容,在我們的例子中為零。

這個 reduce() 方法第一次運作,是以我們得到零和“sam”項。是以它隻是做了80 加零并傳回那個值,也就是 80。

該方法第二次運作時,傳回值 80 成為目前總數,我們的下一項是 'john',是以它計算了 86 加上我們目前的總數 80,即 166,并将其放回目前總數。它一直這樣做,直到我們到達數組中的最後一個項目,該項目将作為 totalScore 變量中的總數輸出。

這種方法有點混亂,但是,當你需要對數組中的所有項目進行某種累積操作時,它非常有用,例如,擷取所有項目的總價,每日股票價格等。

8、includes()

此方法不接受函數作為參數。它需要一個參數。它通常用于不需要大量繁重操作的簡單數組中。假設你有一堆水果,

const Fruits = [ 'mango', 'apple', 'orange', 'pineapple', 'lemon']

contains() 方法實作的是一種簡單方法,是檢查某個水果是否在數組中。

const fruits = [ 'mango', 'apple', 'orange', 'pineapple', 'lemon']


const includesApple = fruits.includes('apple')


console.log(includesApple) // this will return true because 'apple' is one of the items inside the array.      

在我看來,這些方法是任何 JavaScript 開發人員都必須知道的,因為數組是最常用于組織的資料結構之一。掌握好這些方法将大大提高你在陣列方面的技能和解決問題的能力。

如果你覺得今天的内容對你有用,清請記得分享給你身邊的開發者朋友們。

感謝你的閱讀,祝程式設計愉快!

學習更多技能

請點選下方公衆号

繼續閱讀