0

使用 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...

4

2 回答 2

0

使用 JavaScript 的原生方法indexOf

startHere = slides.indexOf(anchor);

如果没有找到,它将返回-1


因此,您可以删除您的$.inArray电话,只需执行

startHere = slides.indexOf(anchor);

if (startHere !== -1) {
    // code when anchor is found
}

删除 jQuery 方法调用开销。

文档:http ://www.w3schools.com/jsref/jsref_indexof_array.asp

于 2013-08-12T16:15:32.333 回答
0

来自$.inArray() 文档....

Description: Search for a specified value within an array and return its index (or -1 if not found).
if( window.location.hash != '' ) {
  anchor = window.location.hash;
  var idxWhere = $.inArray(anchor, slides); // this assigns the index to a new var
  if( idxWhere > 0 ) {
    startHere = key;
  }
}
于 2013-08-12T16:05:35.027 回答