检查Array的路径名

时间:2014-03-02 23:03:56

标签: javascript jquery

我有一个问题:

此代码段效果很好:

$(document).ready(function(){         
    var pathname = window.location.pathname;
    if(pathname.indexOf( 'word1' ) > -1){
        // do something    
    }     
});

但是,如果我想检查单词的数组,它不起作用:

$(document).ready(function(){         
    var myArray1 = new Array( "word1","word2","word3","word4" );
    var pathname = window.location.pathname;
    if(pathname.indexOf( myArray1 ) > -1){
        // never executed!   why? 
    }     
});

有人可以帮忙解决这个问题吗?问候!

6 个答案:

答案 0 :(得分:1)

jQuery有一个内置的方法,$.inArray

$(document).ready(function(){         

    var pathname = window.location.pathname;

    if ( $.inArray(pathname, ["word1","word2","word3","word4"] ) != -1 ) {

         // do stuff

    }     
});

然后是正则表达式

$(document).ready(function(){         
    if ( /(word1|word2|word3|word4)/.test(window.location.pathname) ) {
         // do stuff
    }     
});

答案 1 :(得分:0)

如果你想针对一组值测试pathname,我建议循环。您不能将数组对象作为参数发送到indexOf()方法。你只能发送字符串。

$(document).ready(function(){         
    var myArray1 = new Array( "word1","word2","word3","word4" );
    var pathname = window.location.pathname;
    for(stringy in myArray1){
        if(pathname.indexOf( stringy ) > -1){
            console.log('Match Found');
        }   
    }       
});

看这里: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

答案 2 :(得分:0)

string.indexOf不会将数组作为参数,您应该自己处理它,

好的我会让它有点不同,你也可以用Regex,

来做
$(document).ready(function(){         
    var myArray1 = new Array( "word1","word2","word3","word4" );
    var pathname = window.location.pathname;
    if (pathname.match(new RegExp(myArray1.join("|")))) {
       // yes, there is at least one match.
    }
});

我不知道你是否希望它匹配数组中的所有单词。

答案 3 :(得分:0)

indexOf查找另一个字符串中给定字符串的出现次数。所以你不能用数组作为参数来调用它。您必须多次调用它,每个都使用字符串作为参数。

$(document).ready(function(){         
   var myArray1 = new Array( "word1","word2","word3","word4" );
   var pathname = window.location.pathname;
   for(var i=0; i<myArray1.length; i++) {
      if(pathname.indexOf( myArray1[i] ) > -1){
       // will be executed
      }
   }
});

答案 4 :(得分:0)

您可以使用jQuery.grep()

if ($.grep(myArray1, function(word) {
    return pathname.indexOf(word) != -1;
})) {
    // do something
}

或者,使用原生函数:

if (myArray1.some(function(word) {
    return pathname.indexOf(word) != -1;
})) {
    // do something
}

答案 5 :(得分:0)

我提供了一种测试n数量的路径名的方法。

import pathToRegexp from 'path-to-regexp';

const ALLOWED_PATHS = [
  'test',
  'test/:param'
]

const allowed = ALLOWED_PATHS.map((path) => {
  const regex = pathToRegexp(path)
  return regex.test(window.location.pathname);
});

if(allowed.some(Boolean)) {
  // Match
} else {
  // Not Match
}

...

希望这对您有帮助!