javascript'或'声明

sbj*_*uke 0 javascript variables if-statement

var NavAxis='yx';
var url1 = 'file:///C:/Users/Luke/Desktop/Senior%20Project/index.html#/page4'
var url2 = 'file:///C:/Users/Luke/Desktop/Senior%20Project/index.html#/page5'   

if(location.href == (url1 || url2)){
      NavAxis='xy';
}else{
       NavAxis='yx';
} 
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用?我希望它是如此,如果URL是那些声明的NavAxis更改为'xy'

Tro*_*ott 7

你真正想要的是:

if ( location.href === url1 || location.href === url2 )
Run Code Online (Sandbox Code Playgroud)

你写的内容首先评估内括号: (url1 || url2).url1只要url1是真实的(它在你的代码中),这将评估.

因此,如果location.href等于url1但不是,你的情况才会成立url2.


Moh*_*sen 5

JavaScript OR如何工作:

true || true   // true;
true || false  // true;
false || false // false;
0 || true      // 0 will translate to boolean because other side is boolean and it returns true
1 || 3         // no translation, returns 1
undefined || 2 // undefined will translated to boolean false. returns 2
null || "wow"  // "wow"
Run Code Online (Sandbox Code Playgroud)

这就是你应该这样做的:

if(location.href == url1 || location.href == url2){
    NavAxis='xy';
}else{
   NavAxis='yx';
}
Run Code Online (Sandbox Code Playgroud)

这适用于两次或三次检查,但如果您有10个网址怎么办?

这是一种更好的方法,使用Array.indexOf()适用于多项检查的方法:

if([url1, url2, url3].indexOf(location.href) != -1 ){
        NavAxis='xy';
    }else{
       NavAxis='yx';
    }
Run Code Online (Sandbox Code Playgroud)


Sal*_*n A 5

url1 || url2将评估为file:///...#/page4(即url1)。所以基本上,你是比较location.hrefurl1所有的时间。要与任一比较,请尝试:

if (location.href == url1 || location.href == url2)
Run Code Online (Sandbox Code Playgroud)