简体   繁体   English

Array.prototype.find用于搜索数组中的Object

[英]Array.prototype.find to search an Object in an Array

I am using Array.prototype.find to search an Object Person in an Array. 我正在使用Array.prototype.find来搜索数组中的Object Person。 I would like use the id to find this Object. 我想用id来找到这个Object。 I've been reading about the method find (ES6) but I don't know why my code is wrong. 我一直在阅读方法find(ES6),但我不知道为什么我的代码错了。

This is my code: 这是我的代码:

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;
}

You're passing the id directly as the thisArg parameter to .find() , but inside buscarPersona you expect this to be an object with a .id property. 您将id作为thisArg参数直接传递.find() ,但在buscarPersona您希望this是一个具有.id属性的对象。 So either 所以要么

  • pass an object: 传递一个对象:

     lisPerson.find(buscarPersona, {id}); function buscarPersona(element, index, array) { return element.id === this.id; } 
  • use this directly: 使用this直接:

     lisPerson.find(buscarPersona, id); function buscarPersona(element, index, array) { // works in strict mode only, make sure to use it return element.id === this; } 
  • just pass a closure 只是通过关闭

     lisPerson.find(element => element.id === id); 

A dirty solution could be added the last_id in the AddressBook's Prototype. 可以在AddressBook's Prototype中添加一个脏的解决方案last_id

So your code would be the following 所以你的代码如下

AddressBook.prototype.getPerson = function(id){
    this.last_id = id;
    return this.lisPerson.find(buscarPersona,this);
}
function buscarPersona(element){
    if(element.id === this.last_id){
        return element;
    }else{
        return false;   
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM