为什么我得到了一个“;未定义的“;使用“”从Find()返回值;这个“;论点

Why Am I Getting an "Undefined" Return Value from Find() Using the "This" Argument?

本文关键字:使用 返回值 论点 这个 Find 一个 为什么 未定义      更新时间:2023-09-26

我正在学习Ethan Brown的"学习JavaScript",有一个例子没有正常工作,我不确定出了什么问题。我正在处理的部分是使用find()方法搜索数组,而没有完成我所期望的操作的特定部分涉及使用带有"this"参数的find(()方法。

我希望这个调用find(),它返回"daniel"Person:

arr.find(p => p.id === daniel.id);

要返回与这次调用find()相同的结果,find也应该返回"daniel"Person:

arr.find(p => p.id === this.id, daniel);

相反,第一个find调用可以正常工作,但第二个调用返回"undefined"。为什么会这样?

以下是完整的代码示例(取自《学习JavaScript》第8章——Ethan Brown):

*注意本书使用ES6

class Person {
  constructor(name) {
    this.name = name;
    this.id = Person.nextId++;
  }
}
Person.nextId = 0;
const james = new Person("Jammes"),
      juliett = new Person("Juliett"),
      daniel = new Person("Daniel"),
      jay = new Person("Jay");
const arr = [james, juliett, daniel, jay];
// option 1: find daniel id by direct comparison 
// successfully returns daniel object
arr.find(p => p.id === daniel.id);
// option 2: find jay id by using "this" arg - 
// should return daniel object, instead returns undefined...
arr.find(p => p.id === this.id, daniel);

Arrow函数从创建它们的作用域继承它们的词法this绑定。

否则,不能使用bindcallapply更改箭头函数的this绑定,这正是find在传入手动thisArg绑定时尝试执行的操作。

尝试使用正则函数来记录差异。

arr.find(function (p) { return p.id === this.id; }, daniel);