簡體   English   中英

將這些嵌套函數從箭頭轉換為舊樣式以及變量會發生什么

[英]Convert these nested functions from arrow to old style and what happens with variables

我正在嘗試從一個列表中查找不在第二個列表中的項目。 幾乎是運氣不好,我讓它工作了,但只有箭頭功能。 對我來說,普通函數更容易閱讀,所以我嘗試轉換它,但結果不是我所期望的。

數據:

const arr1 = [
    {
        "key": 1,
        "val": "one"
    },
    {
        "key": 2,
        "val": "two"
    },
    {
        "key": 3,
        "val": "three"
    }
]

const arr2 = [
    {
        "key": 3,
        "val": "three"
    },
    {
        "key": 4,
        "val": "four"
    },
    {
        "key": 1,
        "val": "one"
    }
]

版本 1

arr1.filter((element) => arr2.findIndex((innerElement) => element.key === innerElement.key) === -1); 
// produces object with key 2

版本 2

arr1.filter(function(element) { 
    return arr2.findIndex(function(innerElement) { 
      element.key === innerElement.key === -1
    })
}) // produces all three objects in arr1

為了使正確的更簡潔,我刪除了額外的括號,它仍然有效:

arr1.filter(element => arr2.findIndex(innerElement => element.key === innerElement.key) === -1);

我在這里遺漏了一個關鍵方面。 我知道 arr1 中的每個項目都傳遞給 function,而內部 function 又將其結果傳遞給另一個 function,表達式可以訪問兩組 arguments 並被執行。 但我想我對訂單或其他東西有錯誤的心理 model。

有人可以解釋每個步驟中發生的事情以及如何思考嗎? 我如何將它變成一個正常的 function?

我將處理很多嵌套結構,我覺得這是一個我想改進的薄弱環節。

謝謝

您需要返回比較的值。 === -1測試必須是findIndex()的結果,而不是在它的回調中。

arr1.filter(function(element) { 
    return arr2.findIndex(function(innerElement) { 
      return element.key === innerElement.key;
    }) === -1;
});

這可以用some()方法簡化。

arr1.filter(function(element) {
  return !arr2.some(function(innerElement) {
    return element.key === innerElement.key
  })
})

暫無
暫無

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

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