Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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
JS或jquery:使用inArray时获取数组索引_Jquery_Arrays_Indexing - Fatal编程技术网

JS或jquery:使用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 !=

使用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 != '' ) {

  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
}