为什么我得到了一个“;未定义的“;使用“”从Find()返回值;这个“;论点
Why Am I Getting an "Undefined" Return Value from Find() Using the "This" Argument?
我正在学习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
绑定。
否则,不能使用bind
、call
或apply
更改箭头函数的this
绑定,这正是find
在传入手动thisArg
绑定时尝试执行的操作。
尝试使用正则函数来记录差异。
arr.find(function (p) { return p.id === this.id; }, daniel);
相关文章:
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- 使用filedownload jquery插件处理FilePathResult返回值
- 即使使用回调函数也无法返回值
- 单击按钮时,使用Javascript调用并返回值
- 使用Javascript数组或JSON来存储AJAX请求的返回值,以备将来使用
- 在节点中使用“返回{值}”是否合适
- 未使用返回值时调用方法
- 仅在javascript中使用返回值
- 在JavaScript中使用返回值作为变量
- 如何在 Javascript 中的另一个函数中使用返回值
- 在 html 输入字段中使用返回值函数
- 只想使用返回值并忽略警报
- 如何使用“返回值”从aspx页面java脚本标记返回值;fireEvent;方法
- 在javascript中的新对象中使用返回值
- 在回调中使用返回值
- 未使用返回值设置变量
- 使用返回值从另一个html页面关闭DIV
- Javascript在另一个函数中使用返回值
- 在jquery的另一个函数参数中使用返回值
- Chrome Cookie API不是't不允许我使用返回值