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

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

<!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

最佳答案

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

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

关于javascript - 搜索单词是否在数组内,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56904474/

10-11 06:04