2015-03-25 22 views
1

我是JS的新手,我正在分析一個長的程序代碼。我無法理解這個功能,只是它試圖從客戶端獲取一個cookie。任何人都可以在這裏指出功能嗎?分析JS代碼在客戶端抓取cookie

function get_cookie(a) { 
     var b = a + "="; 
     var c = ""; 
     if (document.cookie.length > 0) { 
      offset = document.cookie.indexOf(b); 
      if (offset != -1) { 
       offset += b.length; 
       end = document.cookie.indexOf(";", offset); 
       if (end == -1) { 
        end = document.cookie.length; 
       } 
       c = unescape(document.cookie.substring(offset, end)); 
      } 
     } 
     return c; 
    } 

回答

1
function get_cookie(a) { 
     var b = a + "="; // Getting argument a and assigning it to var b appending = 
     var c = ""; // defining variable c 
     if (document.cookie.length > 0) { //checking cookie length in browser 
      offset = document.cookie.indexOf(b); // checking b exists or not 
      if (offset != -1) { // if b exists 
       offset += b.length; // getting no of string and assigning it to offset 
       end = document.cookie.indexOf(";", offset); //checking if ';' is present 
       if (end == -1) { // if ';' is not there in cookie string, 
        end = document.cookie.length; - // cookie is not set, SO assigning length to the variable end 
       } 
       c = unescape(document.cookie.substring(offset, end)); // assigning those values to c 
      } 
     } 
     return c; // returning new cookie. 
    } 
+1

'如果(偏移!= -1)'< - 沒有意思。如果B _does_存在嗎? – MrMisterMan 2015-03-25 10:48:54

+0

如果'a ='存在於cookie中,則偏移值爲1;如果不存在,則爲-1。所以它的檢查b是否存在? 。所以這是有道理的。 – 2015-03-25 10:51:32

+0

那麼你能給出上述條件的正確定義嗎? – 2015-03-25 10:53:19