gpt4 book ai didi

javascript - javascript indexOf 对字符串和数组的工作方式有何不同?

转载 作者:行者123 更新时间:2023-11-28 19:33:35 26 4
gpt4 key购买 nike

我有字符串和字符串数组。

var strFruit = "Apple is good for health";  
var arrayFruit = ["Apple is good for health"];

var strResult = strFruit.indexOf("Apple"); //strResult shows 0
var arrayResult = arrayFruit.indexOf("Apple"); // arrayResult shows -1

但是如果我使用 arrayFruit.indexOf("Apple is good for health") arrayResult 显示 0。

我的问题是为什么indexOf在数组元素中查找精确匹配而不是在字符串中以及这两种搜索有何不同?

Jsfiddle

P.S:问这个问题的主要原因是我无法理解 indexOf 的源代码。我可以理解它的什么( indexOf) 与字符串和数组。但我不确定如何它与字符串和数组一起工作?( poly fills or source code )。

最佳答案

在数组中搜索时,indexOf 尝试搜索整个字符串。例如:

var arrayFruit = ["Apple", "is", "good", "for", "health"]; 
var arrayResult = arrayFruit.indexOf("Apple"); // arrayResult will be 0

就您而言,数组中只有一项,即表示“Apple is good for health” 的字符串。因此 indexOf 尝试将 "Apple" 与它匹配。自:

"Apple is good for health" != "Apple" 

你得到-1作为答案。如果您搜索整个字符串,它会给您 0

var arrayResult =  arrayFruit.indexOf("Apple is good for health"); /arrayResult will be 0

关于javascript - javascript indexOf 对字符串和数组的工作方式有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26313644/

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