what does the number 1 do in this code
I understand (I think) that this JavaScript splits on the hash tag, but what would the 1 represent?
win开发者_如何学运维dow.location.hash.split("#")[1];
The split() method is used to split a string into an array of substrings, and returns the new array. Thus, the [1]
represents the second element of the split array window.location.hash.split("#")[1];
JavaScript Split Function
var hashString = "#it #is #easy #to #understand #arrays";
/*
hashString.split("#")[0] = ""
hashString.split("#")[1] = "it "
hashString.split("#")[2] = "is "
hashString.split("#")[3] = "easy "
hashString.split("#")[4] = "to "
hashString.split("#")[5] = "understand "
hashString.split("#")[6] = "arrays"
*/
The reason why split("#")[0] is an empty string is because the split function encounters a "#" at the very start of the string, at which point it creates an entry into the array that includes every character it has passed so far, with the exception of the "#". Since it has passed no characters so far, it creates an entry that is an empty string.
Here's another example:
var hashString = "it #is #easy #to #understand #arrays";
/*
hashString.split("#")[0] = "it "
hashString.split("#")[1] = "is "
hashString.split("#")[2] = "easy "
hashString.split("#")[3] = "to "
hashString.split("#")[4] = "understand "
hashString.split("#")[5] = "arrays"
*/
It accesses the second element found from the split.
An easier way to strip off the hash (#
) is...
var hash = window.location.hash.substr(1);
split()
returns an array, [1]
grabs the 2nd element in the array [0]
would grab the first element.
精彩评论