[英]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.