搜索单词是否在数组内

时间:2019-07-05 13:56:41

标签: javascript

我有这个脚本,想让它搜索数组中是否只有Mango这个词,如果它是真正的console.log它的索引。

我已经尝试过下面的代码,但是它总是失败(false)。

<!DOCTYPE html>
<html>

<body>
    <h1>Array includes()</h1>
    <p>Check if the fruit array contains "Mango":</p>
    <p id="demo"></p>
    <p><strong>Note:</strong> The includes method is not supported in Edge 13 (and earlier versions).</p>
    <script>
        var fruits = ["Banana is yellow", "Orange juice", "Apple is red", "Mango is orange"];
        var n = fruits.includes("Mango");
        console.log(n);
    </script>
</body>

</html>

我需要它返回它所在的索引= 4

3 个答案:

答案 0 :(得分:6)

您要查找索引是字符串包含的子字符串:

  fruits.findIndex(fruit => fruit.includes("Mango"))

答案 1 :(得分:3)

尝试一下:

const fruits = ["Banana is yellow", "Orange juice", "Apple is red", "Mango is orange"];
const getIndex = srch => fruits.findIndex(ele => ele.indexOf(srch)>-1);

console.log(getIndex("Mango"))

答案 2 :(得分:1)

如果必须支持IE(IE不支持findIndex),则可以使用如下所示的smth:

var fruits = ["Banana is yellow", "Orange juice", "Apple is red", "Mango is orange"];
var index;
fruits.forEach((el, i) => {
    if(el.toLowerCase().indexOf('Mango'.toLowerCase()) !== -1) {
        index = i;
    }
});
console.log(index);