JS或jquery:使用inArray时获取数组索引
使用inArray时,如何获取匹配数组值的索引 我现在有这个JS或jquery:使用inArray时获取数组索引,jquery,arrays,indexing,Jquery,Arrays,Indexing,使用inArray时,如何获取匹配数组值的索引 我现在有这个 startHere = 0 var slides = new Array(); slides[0] = "home"; slides[1] = "about"; slides[2] = "working"; slides[3] = "services"; slides[4] = "who"; slides[5] = "new"; slides[6] = "contact"; if( window.location.hash !=
startHere = 0
var slides = new Array();
slides[0] = "home";
slides[1] = "about";
slides[2] = "working";
slides[3] = "services";
slides[4] = "who";
slides[5] = "new";
slides[6] = "contact";
if( window.location.hash != '' ) {
anchor = window.location.hash;
if( $.inArray(anchor, slides) ) {
startHere = key;
}
}
提前感谢您的建议,
K.来自
使用JavaScript的本机方法
indexOf
:
startHere = slides.indexOf(anchor);
如果未找到,它将返回-1
因此,您可以删除
$.inArray
调用,只需执行以下操作即可
startHere = slides.indexOf(anchor);
if (startHere !== -1) {
// code when anchor is found
}
删除jQuery方法调用开销
文档:
$。inArray
返回索引。感谢您的快速响应。我已经阅读了文档,但是我不知道如何将索引值分配给一个新的var!你能解释一下吗?:)
startHere = slides.indexOf(anchor);
startHere = slides.indexOf(anchor);
if (startHere !== -1) {
// code when anchor is found
}