JS - What is the difference here?

女生的网名这么多〃 提交于 2019-12-24 06:42:37

问题


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...

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


回答1:


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

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:

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



回答2:


The second just check if the url contains #register, the first the url path, you can do it also with location.hash

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



回答3:


The first one performs an exact match between window.location.pathname and /#register. The second one looks for #register anywhere in document.URL.




回答4:


This if block check the strings whether they are equal or not

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

 // Code

}

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

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

   // Code...

}


来源:https://stackoverflow.com/questions/16733432/js-what-is-the-difference-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!