JS或jquery:使用inArray时获取数组索引

时间:2013-08-12 16:02:15

标签: 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 != '' ) {

  anchor = window.location.hash;

  if( $.inArray(anchor, slides) ) {
    startHere = key;
  }

}

提前感谢任何建议, ķ...

2 个答案:

答案 0 :(得分:0)

来自$.inArray() documentation ....

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;
  }
}

答案 1 :(得分: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