javascript - Array.prototype.find 在数组中搜索对象

标签 javascript arrays find ecmascript-6

我正在使用 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/

相关文章:

javascript - 天/小时热图 + mySQL

javascript - 如何阻止简单的 Discord 机器人 ping 用户?

arrays - Matlab - 两条线的距离

arrays - 我应该如何有选择地对数组的多个轴求和?

php - 按分解的键字符串对数组进行分组

emacs rgrep 在 find 命令中失败 (Windows 7)

python - 如何使用 Beautiful Soup 的 find() 代替 find_all() 以获得更好的运行时间

javascript - onchange 仅检测 div 的第一个复选框

javascript - 如何仅使用客户端 JavaScript 正确签署对亚马逊 ItemLookup 的 GET 请求?

javascript - 如何在JQuery中显示隐藏使用最接近和查找方法选择的元素?