带对象的IndexOf数组

时间:2017-10-20 16:51:02

标签: javascript arrays object indexof

我有一个包含对象的数组。我试过了indexOf,但它没有用。



let tags = [];

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

console.log(tags.indexOf("hello"));




我正在尝试类似的东西,标签有一些价值,我只是不想添加所有代码。

有没有解决办法,只用数行来比较数组中的文本和字符串?

2 个答案:

答案 0 :(得分:2)

您可以使用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; }




答案 1 :(得分:2)

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

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