Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按包含字符串的名称获取对象索引_Javascript_Jquery_Arrays - Fatal编程技术网

Javascript 按包含字符串的名称获取对象索引

Javascript 按包含字符串的名称获取对象索引,javascript,jquery,arrays,Javascript,Jquery,Arrays,我使用jQuery toArray()方法创建了一个JS数组,其中包含一个div中的所有li元素。现在我尝试获取数组的索引,该数组包含一个特定字符串:showing 我尝试了.index、.filter,但都给出了相同的错误消息 arraySlides.index is not a function logic.js:218 Uncaught TypeError: showing is not a function 这是我的阵列: [li.slide.showing, li.slide, li

我使用jQuery toArray()方法创建了一个JS数组,其中包含一个div中的所有li元素。现在我尝试获取数组的索引,该数组包含一个特定字符串:showing

我尝试了.index、.filter,但都给出了相同的错误消息

arraySlides.index is not a function
logic.js:218 Uncaught TypeError: showing is not a function
这是我的阵列:

[li.slide.showing, li.slide, li.slide]
0:li.slide.showing
1:li.slide
2:li.slide
length:3
__proto__:Array(0)
因为我试图找到一个字符串,所以它不起作用吗

var current = arraySlides.index('showing');

好吧,也许我不清楚。我正在尝试获取索引,因此类名在数组中所包含位置的数字显示..

您应该使用indexOf()方法

正如您所知,indexOf()方法返回数组中可以找到给定元素的第一个索引,如果该元素不存在,则返回-1。语法如下所示

arr.indexOf(searchElement) 


我不相信您看到的是
过滤器不是一个函数
。您可能会看到更像是
的东西,显示不是一个函数

[]过滤器('显示')
var arr=$('li').toArray();
控制台日志(arr);
console.dir(searchStringInArray('showing',arr));
函数searchStringInArray(str,strArray){

对于(var j=0;j我只是提供了一种方法来获取包含子字符串
的数组元素的
索引
,显示
,因为这里的其他答案似乎为您提供了一种在数组中搜索整个字符串的方法

var值=[“li.slide”、“li.slide.showing”、“li.slide”];
$.each(值、函数(索引、值){
if(value.includes('showing')){
log(“在索引:+index处找到”);
}
});

该方法称为
indexOf
,而不是
index
。然而,
filter
是一个现存的方法,所以我很惊讶你看到了一个非函数错误,除非你使用的是旧浏览器。感谢你给出了这个广泛的答案,但我需要搜索类名,就像下面的答案一样。仍然给你一些提示因为这个答案太棒了solid@HuubS更新。包括如何在结尾处获取索引。太棒了,但是我从中获取了类名,是否也可以获取数组中的位置(因此1、2等)?
arr.indexOf(searchElement) 
arr.indexOf(searchElement, fromIndex)