如果url的索引为x或y,则不要执行以下操作

时间:2019-06-03 14:24:20

标签: javascript

我认为我在语法上遇到麻烦。我想说的是,如果URL的索引为425,或者URL的索引为297,则不要运行以下命令。这仅适用于一个:

    if (document.location.href.indexOf('425') === -1){ 

但是当我尝试添加它的第二个索引不起作用时,这是我尝试过的内容

//attempt 1
    if (document.location.href.indexOf('425') === -1 || document.location.href.indexOf('297') === -1){ 

}
//attempt 2
    if ((document.location.href.indexOf('425')) === -1 || (document.location.href.indexOf('297')) === -1)){ 

}

2 个答案:

答案 0 :(得分:3)

  

我要说的是,如果该网址的索引为425,或者该网址的索引为297,请不要运行以下内容。

或者换句话说,如果URL 没有有425个 没有则有297个,请执行以下操作:

if (document.location.href.indexOf('425') === -1 && document.location.href.indexOf('297') === -1){

=== -1表示找不到。

但是现在,您可以使用includes(如果需要支持IE,则可以为IE进行注浆):

if (!document.location.href.includes('425') && !document.location.href.includes('297')){

答案 1 :(得分:2)

您需要一个logical AND &&,因为两个部分都必须是true

if (
    document.location.href.indexOf('425') === -1 &&
    document.location.href.indexOf('297') === -1
) { 
    // ...
}

对于多个值,您可以将不需要的部分作为数组并使用Array#every进行检查。

if ['425', '297'].every(s => !document.location.href.includes(s))) {
    // ...
}