代码之家  ›  专栏  ›  技术社区  ›  Aalksv

带对象的数组索引[闭合]

  •  -1
  • Aalksv  · 技术社区  · 8 年前

    我有一个包含对象的数组。我试过了 indexOf 但它不起作用。

    let tags = [];
    
    let tag = {
      text: "hello",
      element: document.createElement('span')
    };
    tags.push(tag);
    
    console.log(tags.indexOf("hello"));

    我试着这样做,标签有一些值,我只是不想添加所有代码。

    2 回复  |  直到 8 年前
        1
  •  2
  •   Hassan Imam Ravi kant    8 年前

    您可以使用 array#filter 筛选出包含给定文本的标记。

    let tags = [{
            text: 'hello',
            element: document.createElement('span')
    }, {
            text: 'there',
            element: document.createElement('div')
    }, {
            text: 'world',
            element: document.createElement('span')
    }, {
            text: 'hello',
            element: document.createElement('span')
    }];
    
    let result = tags.filter(tag => tag.text === 'hello');
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
        2
  •  2
  •   djfdev    8 年前

    接受的答案返回一个数组,其中包含通过筛选函数的所有标记。但最初的问题似乎是寻找一种方法来找到一个特定标签的索引。您可以使用 Array.prototype.findIndex ,它接受要测试的函数:

    tags.findIndex(tag => tag.text === 'hello')