Javascript indexOf始终为document.location返回true
我有以下脚本:Javascript indexOf始终为document.location返回true,javascript,dom,Javascript,Dom,我有以下脚本: if (window.location.href.indexOf('env=P')) { env = 'P'; console.log("P"); } else { env = 'A'; console.log("A"); } 无论url是什么,env始终等于p。我很确定我以前对uri使用过indexOf,但不确定这里的问题。indexOf将返回-1,如果子字符串不在字符串中,并且-1是true值 这是因为它返回子字符串的索引(因此返回的是0)
if (window.location.href.indexOf('env=P')) {
env = 'P';
console.log("P");
} else {
env = 'A';
console.log("A");
}
无论url是什么,env始终等于p。我很确定我以前对uri使用过indexOf,但不确定这里的问题。
indexOf
将返回-1
,如果子字符串不在字符串中,并且-1
是true
值
这是因为它返回子字符串的索引(因此返回的是0
)
您的支票应为:
if (location.href.indexOf('env=P') >= 0) {
indexOf
返回-1如果没有匹配项,这是一个真实值,则需要显式
if (window.location.href.indexOf('env=P') === -1) {
///no match
这是因为indexOf不返回0,因此计算结果为true。试着换成
if (window.location.href.indexOf('env=P') > -1)