我有一个getter从cookie中获取值。

现在我有了两个cookie,名字分别是shares=和obligation =。

我想让这个getter只从义务cookie中获取值。

我怎么做呢?因此for语句将数据拆分为单独的值,并将其放入数组中。

 function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie? 
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }

当前回答

关于如何得到饼干,这里已经有了很好的答案,但这是我自己的解决方案:

function getcookie(cookiename){
var cookiestring  = document.cookie;
var cookiearray = cookiestring.split(';');
for(var i =0 ; i < cookiearray.length ; ++i){ 
    if(cookiearray[i].trim().match('^'+cookiename+'=')){ 
        return cookiearray[i].replace(`${cookiename}=`,'').trim();
    }
} return null;
}

用法:“

     getcookie('session_id');
   // gets cookie with name session_id

其他回答

我会这样做:

function getCookie(cookie){
  return cookie
    .trim()
    .split(';')
    .map(function(line){return line.split(',');})
    .reduce(function(props,line) {
      var name = line[0].slice(0,line[0].search('='));
      var value = line[0].slice(line[0].search('='));
      props[name] = value;
      return props;
    },{})
}

这将以对象的形式返回cookie。

然后你可以这样调用它:

getCookie(document.cookie)['shares']

我喜欢使用闭包按名称获取cookie值。下面的闭包将允许您通过名称获取cookie值,但只有在更新了cookie字符串时才会解析cookie字符串。

您可以通过以下方法检索cookie的值:

var foo = cookies.get( "bar" );

代码:

var cookies = ( function() {
    var cookieString = null;
    var cookieArray = [];

    function getValOf( name ) {
        if ( newCookies() ) {
            parseCookieString()
        }
        return cookieArray[ name ];
    }

    // Check if new cookies have been added
    function newCookies() {
        return cookieString === document.cookie;
    }

    function parseCookieString() {
        cookieString = document.cookie;

        // Separate cookies
        var cookies = cookieString.split( ";" );

        // Empty previous cookies
        cookieArray = [];

        // Update cookieArray with new name-value pairs
        for ( var i in cookies ) {

            // Separate name and value
            var nameVal = cookies[ i ].split( "=" );
            var name = nameVal[ 0 ].trim();
            var value = nameVal[ 1 ].trim();

            // Add cookie name value pair to dictionary
            cookieArray[ name ] = value;
        }
    }

    return {

        /**
         * Returns value or undefined
         */
        get: function( name ) {
            return getValOf( name );
        }  
    };
})();
const cookies = 'key1=chocolate; key2=iceCream; key3=cookies;';

// convert string into array with split
const arrCookies = cookies.split('; '); // [ 'key1=chocolate', 'key2=iceCream', 'key3=cookies' ]

// split key value by equal sign
const arrArrCookiesKeyValue = arrCookies.map(cookie => [cookie.split('=')]);  // [[['key1', 'chocolate']], ...']

// make an object with key value
const objectKeyValueCookies = {}; // { key1: 'chocolate', key2: 'iceCream', key3: 'cookies;' }
for (let arr of arrArrCookiesKeyValue) {
    objectKeyValueCookies[arr[0][0]] = arr[0][1];
}

// find the key in object
const findValueByKey = (key = null, objectCookies) => objectCookies[key];
console.log(findValueByKey('key2', objectKeyValueCookies)); // chocolate

这对我来说是完美的(假设cookie名称是唯一的):

function getCookie(name) {
    var cookies = document.cookie;
    var parts = cookies.split(name + "=");
    var cookieValue = '';
    if (parts.length == 2) {
        cookieValue = parts.pop().split(";").shift();
    }
    return cookieValue;
}

一行转换cookie为JavaScript对象或地图

Object.fromEntries(document.cookie.split('; ').map(v=>v.split(/=(.*)/s).map(decodeURIComponent)))
new Map(document.cookie.split('; ').map(v=>v.split(/=(.*)/s).map(decodeURIComponent)))