簡體   English   中英

JavaScript Array.prototype.find第二個參數thisArg不起作用

[英]Javascript Array.prototype.find second argument thisArg not working

我正在閱讀一本JavaScript書,找到了有關如何使用arr.find(callback[, thisArg])

class Person {
    constructor(name) {
        this.name = name;
        this.id = Person.nextId++;
    }
}

Person.nextId = 0;

const jamie = new Person("Jamie"),
      juliet = new Person("Juliet"),
      peter = new Person("Peter"),
      jay = new Person("Jay");
const arr = [jamie, juliet, peter, jay];

// option 2: using "this" arg:
arr.find(p => p.id === this.id, juliet); // returns juliet object

我無法獲得理想的結果。 每當find()返回undefined

您正在使用arrow功能,該功能保留詞法作用域。 arrow函數中的this變量表示window而不是您傳遞的juliet參數。

為了解決這個問題,您可以簡單地使用function創建新的作用域並this傳遞juliet

 class Person { constructor(name) { this.name = name; this.id = Person.nextId++; } } Person.nextId = 0; const jamie = new Person("Jamie"), juliet = new Person("Juliet"), peter = new Person("Peter"), jay = new Person("Jay"); const arr = [jamie, juliet, peter, jay]; // option 2: using "this" arg: let a = arr.find(function(p) { return p.id === this.id; }, juliet); console.log(a); 

暫無
暫無

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

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