簡體   English   中英

如何在 JavaScript 中使用 forEach 替換 for 循環?

[英]How to use replace for loop using forEach in JavaScript?

我有一個對象數組的 for 循環,我需要使用數組方法替換 for 循環。 我想如果使用每個或地圖,我研究並閱讀了文檔,但我無法替換它,也無法理解如何替換。 我有幾行代碼要在 for 循環中運行。但是所有的文檔和理論只涉及 console.log,我不知道如何在 for Each 方法中合並這么多行代碼。

for ( var i = 0; i < points.length; i++ ) {

  let point = points[i];
  if ( point.x*x < 0 || point.y*y < 0 )
      continue; 

  let magnitude = point.x*x + point.y*y;

  if ( magnitude > max_magnitude ) {
      max_magnitude = magnitude;
      max_index = i;
  }

}

點是一個對象數組。 它由向量及其 x 和 y 坐標組成。

forEach 函數接受一個回調,該回調將接收 3 個參數。 第一個參數是被迭代的項目,第二個參數是當前項目的索引。 你的代碼可以這樣重寫:

points.forEach((point, i) => {

    if ( point.x*x < 0 || point.y*y < 0 )
        return; 

    let magnitude = point.x*x + point.y*y;

    if ( magnitude > max_magnitude ) {
        max_magnitude = magnitude;
        max_index = i;
    }
})

您可能錯過了這樣一個事實,即您傳遞給.forEach()函數也可以將當前索引作為參數。 所以它看起來像這樣:

points.forEach((point, i) => {

  if ( point.x*x < 0 || point.y*y < 0 )
      continue; 

  let magnitude = point.x*x + point.y*y;

  if ( magnitude > max_magnitude ) {
      max_magnitude = magnitude;
      max_index = i;
  }

});

你說你需要用數組方法替換循環。 通常的理由(或者我教我的學生)是數組方法更清楚地記錄了你想要做什么。 如果您有一個 for 循環用於查找匹配某個條件的第一個值,則應使用.find 如果要查找所有匹配的值,請使用.filter 如果您想要逐項轉換,請使用.map 如果要檢查每個項目是否與給定條件匹配,請使用.every 如果要檢查某些項目是否符合條件,請使用.some 如果您想將數組轉換為單個值,請使用.reduce

請注意此列表中沒有的內容: forEach 雖然forEach沒有任何問題,但它並沒有真正添加任何有用的語義。 當傳遞給forEach的函數可獨立重用並且您不適合上述任何類別時,這將非常有用。

讓我們看看你想做什么。 您正在將點轉換為幅度,然后選擇最大值。 我們可以通過使用map進行轉換,然后使用Math.max來找到最大值。 它看起來像這樣:

 const points = [{x: 1, y: 2}, {x: 8, y: 6}, {x: 7, y: 5}, {x: 3, y: 0}] const max_magnitude = Math .max (0, ... points .map (({x, y}) => x * x + y * y)) console .log (max_magnitude) //=> 100 (8 * 8 + 6 * 6)

我們將0添加到最大調用,以便為空數組提供最小值。

(我還在對問題的評論中做出了假設,即point.x * x應該是point.x * point.x ,對於y 。在談論幅度時這是有道理的,但如果它是錯誤的,代碼將不得不稍微改變。)

但是您正在計算兩件事,最大震級和具有最大震級的點的索引。

為此,我會切換到reduce 我們本可以只為最大值使用reduce ,但Math.max簡化了它。 由於我們必須做進一步的計算, reduce變得更簡單。

所以也許我們可以這樣寫:

 const points = [{x: 1, y: 2}, {x: 8, y: 6}, {x: 7, y: 5}, {x: 3, y: 0}] const results = points .reduce ( ({max, index}, {x, y}, i) => x * x + y * y > max ? {max: x * x + y * y, index: i} : {max, index}, {max: -Infinity, index: -1} ) console.log (results) //=> {max: 100, index: 1}

為了取回原始變量,我們可以用const {max: max_magnitude, index: max_index} = ...替換const results = ... const {max: max_magnitude, index: max_index} = ...

這些數組方法有助於更清楚地了解循環代碼可能模糊的內容。 絕對值得學習它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM