Javascript Array.prototype.find第二个参数thisArg不工作

Javascript Array.prototype.find第二个参数thisArg不工作,javascript,Javascript,我在读一本JavaScript书,发现了关于如何使用arr.find(callback[,thisArg]) 我不能得到想要的结果。每次find()返回undefined 您正在使用arrow函数,这些函数保留词法范围。arrow函数中的this变量表示window,而不是您传递的juliet参数 要纠正这一点,只需使用函数创建新的作用域并将juliet作为this传递即可 班级人员{ 建造师(姓名){ this.name=名称; this.id=Person.nextId++; } } Pe

我在读一本JavaScript书,发现了关于如何使用
arr.find(callback[,thisArg])


我不能得到想要的结果。每次
find()
返回
undefined

您正在使用
arrow
函数,这些函数保留词法范围。arrow函数中的
this
变量表示
window
,而不是您传递的
juliet
参数

要纠正这一点,只需使用
函数
创建新的作用域并将
juliet
作为
this
传递即可

班级人员{
建造师(姓名){
this.name=名称;
this.id=Person.nextId++;
}
}
Person.nextId=0;
康斯特·杰米=新人(“杰米”),
朱丽叶=新人(“朱丽叶”),
彼得=新人(“彼得”),
jay=新人(“jay”);
const arr=[jamie,juliet,peter,jay];
//选项2:使用“this”参数:
设a=arr.find(函数(p){
返回p.id==this.id;
}朱丽叶);

控制台日志(a)
您正在使用
arrow
函数,这些函数保留词法范围。arrow函数中的
this
变量表示
window
,而不是您传递的
juliet
参数

要纠正这一点,只需使用
函数
创建新的作用域并将
juliet
作为
this
传递即可

班级人员{
建造师(姓名){
this.name=名称;
this.id=Person.nextId++;
}
}
Person.nextId=0;
康斯特·杰米=新人(“杰米”),
朱丽叶=新人(“朱丽叶”),
彼得=新人(“彼得”),
jay=新人(“jay”);
const arr=[jamie,juliet,peter,jay];
//选项2:使用“this”参数:
设a=arr.find(函数(p){
返回p.id==this.id;
}朱丽叶);
控制台日志(a)
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