indexOf 始终为 document.location 返回 true

jef*_*lte 3 javascript dom

我有以下脚本:

if (window.location.href.indexOf('env=P')) {      
  env = 'P';
  console.log("P");
} else {
  env = 'A';
  console.log("A");
}   
Run Code Online (Sandbox Code Playgroud)

不管 url 是什么,env 总是等于 P。我很确定我之前对 uri 使用过 indexOf,但不确定这里的问题。

jjr*_*rdk 5

那是因为 indexOf 不返回 0,因此被评估为 true。尝试更改为

if (window.location.href.indexOf('env=P') > -1)
Run Code Online (Sandbox Code Playgroud)