使用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;
}
}
提前感谢任何建议, ķ...
答案 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方法调用开销。