简体   繁体   English

JS-这里有什么区别?

[英]JS - What is the difference here?

I'm a newbie to JS and it would be extremely useful to know what the differenece is between the following two if statement conditions... 我是JS的新手,知道以下两个if语句条件之间的区别是非常有用的...

First condition (not actually working): 第一个条件(实际上不起作用):

if ( window.location.pathname == '/#register' ) {

// Code

}

Second condition: 第二个条件:

if (document.URL.indexOf("#register") >= 0) {

// Code...

}

FYI, this would help me solve a bug I'm experiencing here 仅供参考,这将帮助我解决我在这里遇到的错误

The first checks for an exact match. 第一个检查完全匹配。 And it does it on the pathname, which doesn't include the hash, so it probably doesn't do what you want. 而且它是在不包含哈希的路径名上完成的,因此它可能并没有满足您的要求。

The second one checks the string contains "#register" , so the full path could be bigger, like /#register_or_not or /some/other/path#register 第二个检查字符串是否包含"#register" ,因此完整路径可能更大,例如/#register_or_not/some/other/path#register

Probably your best option would be to do a regex pattern match on the URL, to ensure that the hash it matches is ONLY 'register', while allowing the rest of the URL to be whatever: 可能最好的选择是对URL进行正则表达式模式匹配,以确保其匹配的哈希仅“注册”,同时允许URL的其余部分为任意值:

if (document.URL.match(/.*#register$/)) {

第二个只是检查网址是否包含#register,第一个是网址路径,您也可以使用location.hash

if(location.hash=='#register') { //....

The first one performs an exact match between window.location.pathname and /#register . 第一个在window.location.pathname/#register之间执行完全匹配。 The second one looks for #register anywhere in document.URL . 第二个在document.URL任何地方查找#register

This if block check the strings whether they are equal or not 这个if块检查字符串是否相等

if ( window.location.pathname == '/#register' ) {

 // Code

}

The indexOf() method returns the position of the first occurrence of a specified value in a string. indexOf()方法返回字符串中第一次出现指定值的位置。

This method returns -1 if the value to search for never occurs. 如果要搜索的值永不出现,则此方法返回-1。

if (document.URL.indexOf("#register") >= 0) {

   // Code...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM