【问题标题】:JS or jquery: get array index when using inArrayJS 或 jquery:使用 inArray 时获取数组索引
【发布时间】:2013-08-12 16:02:14
【问题描述】:

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

}

提前感谢您的任何建议, 克...

【问题讨论】:

  • $.inArray 返回索引。

标签: jquery arrays indexing


【解决方案1】:

来自$.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;
  }
}

【讨论】:

  • 感谢您的快速回复。我已经阅读了文档,但我无法弄清楚如何将索引值实际分配给新的 var!你能解释一下吗? :)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2011-03-20
    • 2012-07-14
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多