简体   繁体   English

JavaScript Array.prototype.find第二个参数thisArg不起作用

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

I was reading a JavaScript book and found this code about how to use arr.find(callback[, thisArg]) 我正在阅读一本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

I cannot get the desired result. 我无法获得理想的结果。 Everytime the find() returns undefined . 每当find()返回undefined

You are using arrow functions, which preserve lexical scoping. 您正在使用arrow功能,该功能保留词法作用域。 The this variable inside your arrow function represents window and not the juliet argument you have passed. arrow函数中的this变量表示window而不是您传递的juliet参数。

To rectify this, you can simply use function to create new scope and pass juliet as this . 为了解决这个问题,您可以简单地使用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