See that the following function is used to obtain the value of the url.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
But I don’t know what expression [,null] is here.
The purpose of this function is to get the value of a certain parameter in the URI, such as the URL
http://www.xxx.com/index.html?key=hello&value=world*
. At this time,location.search
is equal to?key=hello&value=world
. For example, to get the value ofkey
("hello"), just callgetURLParameter("key")
.The syntax of exec is as follows:
If it matches, the return result is an array. The first element of the array is the matched substring, and the subsequent elements are the contents of the capturing brackets. As can be seen from the regular expression, the result we need is the th The content of a capturing bracket is the second element of the array, so
is used[1]
;For example, assuming the URL is still the one above, we call
getURLParameter("key")
, and the matching result is["key=hello&", "hello", "&"]
,"key=hello& "
is the matched substring,"hello"
is the content of the first capturing bracket,"&"
is the content of the second capturing bracket.["key=hello&", "hello", "&"] || [,null]
The result is of course the previous item, which is["key=hello&", "hello", "&"]
, then take[1]
, and the return value of the entire function is"hello"
.However, if we call
getURLParameter("time")
, the matching fails, so the result is null. At this time, if you call[1]
, an error will be reported.[,null]
means[undefined, null]
. When the matching fails, it becomesnull || [undefined, null]
. This result is[undefined, null]
. At this time,[1]
No error will be reported. At this time, the entire function returnsnull
.After calling the
getURLParameter
function, you can determine whether the return value is null. If it is null, it means there is no such parameter in the URL; if it is not null, the return value is the required parameter value.Lazy approach,
(name + '=' + '(.+?)(&|$)').exec(location.search)
If the match is successful. The result will not be null.(.+?)
is the regular matching value[1]
. If the match fails, exec returns null.[,null]
The first value isundefined
. This operation only unifies the return value to null. The key is that the last[1]
causesIf the latter one is
[0]
, then[,null]
can be rewritten as[null]
[,null][1] Isn’t it null? If the previous one is not matched, null will be returned
It’s equivalent to this
But if the parameter value is not obtained in the previous section (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) ), an error will be reported if [1] is taken directly. So adding [,null] at the end is equivalent to [undefined, null], and taking [1] at the end can ensure that array out-of-bounds errors will not occur because the url parameters cannot be obtained