gpt4 book ai didi

javascript - 搜索一个词是否在数组中

转载 作者:行者123 更新时间:2023-12-03 12:44:02 25 4
gpt4 key购买 nike

我有这个脚本,如果数组中只有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com