我正在使用 Array.prototype.find 在数组中搜索对象人物。我想使用 id 来找到这个对象。我一直在阅读有关查找方法 (ES6) 的信息,但我不知道为什么我的代码是错误的。
这是我的代码:
AddresBook.prototype.getPerson = function (id) {
return this.lisPerson.find(buscarPersona, id);
};
function buscarPersona(element, index, array) {
if (element.id === this.id) {
return element;
} else
return false;
}
最佳答案
您将 id
作为 thisArg
parameter to .find()
直接传递,但在 buscarPersona
中,您希望 this
是一个具有 .id
属性的对象。所以要么
传递一个对象:
lisPerson.find(buscarPersona, {id}); function buscarPersona(element, index, array) { return element.id === this.id; }
直接使用
this
:lisPerson.find(buscarPersona, id); function buscarPersona(element, index, array) { // works in strict mode only, make sure to use it return element.id === this; }
只是传递一个闭包
lisPerson.find(element => element.id === id);
关于javascript - Array.prototype.find 在数组中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997278/