One approach, which avoids iterating over an array, would be:(一种避免迭代数组的方法是:)
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
Walkthrough(演练)
Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string .(如果令牌中不存在令牌,则按令牌拆分字符串将生成一个具有一个字符串(相同值)的数组,或者如果在string中找到令牌,则将生成具有两个字符串的数组。)
The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token.(第一个(左)元素是令牌之前的字符串,第二个(右)元素是令牌之后的字符串。)
(NOTE: in case string starts with a token, first element is an empty string)((注意:如果字符串以令牌开头,则第一个元素为空字符串))
Considering that cookies are stored as follows:(考虑到cookie的存储方式如下:)
"{name}={value}; {name}={value}; ..."
in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";".(为了检索特定的cookie值,我们只需要获取在“; {name} =”之后和下一个“;”之前的字符串。)
Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=":(在进行任何处理之前,我们在cookie字符串前添加“;”,以便每个cookie名称(包括第一个)都用“;”和“ =“括起来:)
"; {name}={value}; {name}={value}; ..."
Now, we can first split by "; {name}=", and if token is found in a cookie string (ie we have two elements), we will end up with second element being a string that begins with our cookie value.(现在,我们首先可以用“; {name} =”进行拆分,如果在cookie字符串中找到了令牌(即,我们有两个元素),我们将以第二个元素作为以cookie值开头的字符串结尾。)
Then we pull that out from an array (ie pop), and repeat the same process, but now with ";"(然后我们将其从数组中取出(即pop),并重复相同的过程,但现在使用“;”) as a token, but this time pulling out the left string (ie shift) to get the actual token value.(作为令牌,但是这次拉出左字符串(即shift)以获取实际令牌值。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…