簡體   English   中英

帶有箭頭函數回調的Array.prototype.filter()參數? (無此綁定)

[英]Array.prototype.filter() argument with arrow function callback? (no this binding)

編輯:這已被錯誤地標記為重復(請參閱注釋中的討論)本文作者在此處提供了針對此特定問題的解決方案

https://hackernoon.com/rethinking-javascript-death-of-the-for-loop-c431564c84a8的啟發,我一直在重構一些舊代碼。

使用Array.prototype.filter傳遞參數時遇到問題,因為Array.prototype.filter(callback,thisArg)的第二個參數綁定了回調中的“ this”對象,但是箭頭函數不綁定“ this”。

在我的示例中,我通過使用“ Object.keys()”從關聯數組中獲取鍵(是的,我知道,技術上在js中不可用),然后通過關聯數組中其對象的屬性過濾該數組。 [item] .property”,但由於此綁定不可用而失敗。

因此,采用箭頭功能,如何將參數傳遞給filter()中的回調?

 const arr = { a: { property: true, otherProp: false }, b: { property: true, otherProp: false }, }, hasProperty = item => this[item].property, getMatchingKeys = object => Object.keys(object).filter(hasProperty, object); getMatchingKeys(arr); 

您可以使用Object.entries 它同時提供了鍵和值,因此您不需要引用該對象本身:

 const arr = { a: { property: true, otherProp: false }, b: { property: true, otherProp: false }, c: { property: false, // to be excluded otherProp: true }, }, hasProperty = ([key, value]) => value.property, first = ([key]) => key, getMatchingKeys = object => Object.entries(object).filter(hasProperty).map(first); console.log(getMatchingKeys(arr)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您還可以使用bind不是綁定this ,而是第一個參數:

 const arr = { a: { property: true, otherProp: false }, b: { property: true, otherProp: false }, c: { property: false, // to be excluded otherProp: true }, }, hasProperty = (object, key) => object[key].property, getMatchingKeys = object => Object.keys(object).filter(hasProperty.bind(null, arr)); console.log(getMatchingKeys(arr)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

請參閱我對另一個問題的回答中的其他一些選項。

本文的作者在評論中提供了答案,在此提供參考:

const arr = {
  a: {
    property: true,
    otherProp: false,
  },
  b: {
    property: true,
    otherProp: false,
  },
}
const hasProperty = object => item => object[item].property
const getMatchingKeys = object => Object.keys(object).filter(hasProperty(arr))
getMatchingKeys(arr) // = ['a', 'b']

@bergi在原始帖子的評論中提供的進一步閱讀(深埋,在此處發布以提高可見度):

  1. jQuery將更多參數傳遞給回調
  2. 如何在Javascript .filter()方法中將額外的參數傳遞給回調函數?

暫無
暫無

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

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