【问题标题】:Retrieve first matching object in array by boolean通过布尔值检索数组中的第一个匹配对象
【发布时间】:2019-11-24 17:14:06
【问题描述】:

如何在下面的数组中检索带有free:true 的第一个对象而不自己循环遍历它?有单行吗?

var leftCoords = [{x: 60, y: 192, free: false}, {x: 15, y: 20, free: false}, {x: 435, y: 60, free: true}];

【问题讨论】:

    标签: javascript find boolean


    【解决方案1】:

    您可以使用数组find 方法。

    var leftCoords = [{x: 60, y: 192, free: false}, {x: 15, y: 20, free: false}, {x: 435, y: 60, free: true}];
    
    // Find it
    const found = leftCoords.find(el => el.free);
    console.log(found);
    
    // Now we can set it to false
    found.free = false;
    console.log(leftCoords);

    【讨论】:

    • 很抱歉,我实际上忘记了我的问题还有第二部分。我需要在找到的对象中更改 free 的值,以便 free: true 变为 free: falsefind 做不到,对吧?
    • 已更新。我们可以直接免费发到false
    • 哇,我不知道参考是这样倒退的!非常感谢!
    • 是的,它找到了对象并且仍然指向内存中的同一个对象。
    猜你喜欢
    • 1970-01-01
    • 2021-03-21
    • 2020-04-06
    • 2023-03-24
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多