【问题标题】:How to find Index Number of this array value?如何找到这个数组值的索引号?
【发布时间】:2021-03-17 08:09:21
【问题描述】:

const options = [
{_id: "0175", name: "Ahnaf"},
{_id: "8555", name: "Abir"},
{_id: "8795", name: "Book"},
]

现在如何获取 _id = 8795 的索引? 这意味着我如何获取 index 数字来获取此对象{_id: "8795", name: "Book"}

【问题讨论】:

    标签: javascript arrays object indexing


    【解决方案1】:

    你可以使用.findIndex:

    const options = [
    {_id: "0175", name: "Ahnaf"},
    {_id: "8555", name: "Abir"},
    {_id: "8795", name: "Book"},
    ]
    
    const index = options.findIndex(e => e._id==="8795");
    
    console.log(index);

    【讨论】:

    • @taslimkd 有什么问题?
    • 我无法在这里解释如何发送图片在这里
    • 我已经附上了照片,你现在可以理解这个问题了..
    • 您需要在比较时将ObjectId 转换为String,例如:e._id.toString()。您可以根据所使用的技术对此进行更多研究
    • @taslimkd 您是否记录了这两个值?实际上是在数组内吗?还是它显示-1 是因为没有包含提供的id 的元素?您可以使用== 而不是=== 隐式转换值,因此没有理由调用toString()
    【解决方案2】:

    您需要结合使用 find 和 findIndex 来查找您要查找的索引。

    const options = [
      {_id: "0175", name: "Ahnaf"},
      {_id: "8555", name: "Abir"},
      {_id: "8795", name: "Book"},
      ]
    
    const foundObj = options.find((option) => option._id === "8555")
    const index = options.findIndex((option, index) => {
      if(typeof foundObj !== "undefined" && option._id === foundObj._id) {
        return index
      }else
      return null
    } )
    
    console.log('index', index);
    

    【讨论】:

      猜你喜欢
      • 2016-01-04
      • 1970-01-01
      • 2011-11-12
      • 2018-04-25
      • 2016-08-21
      • 2014-05-19
      • 2019-03-24
      • 1970-01-01
      相关资源
      最近更新 更多