Skip to content

Commit a1e99ef

Browse files
committed
Fix odd result for calling $.cookie() when there are no cookies at all. Closes #212.
1 parent 8f68246 commit a1e99ef

2 files changed

Lines changed: 16 additions & 10 deletions

File tree

‎jquery.cookie.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,14 @@
6262
}
6363

6464
// Read
65-
var cookies = document.cookie.split('; ');
65+
6666
var result = key ? undefined : {};
67+
68+
// To prevent the for loop in the first place assign an empty array
69+
// in case there are no cookies at all. Also prevents odd result when
70+
// calling $.cookie().
71+
var cookies = document.cookie ? document.cookie.split('; ') : [];
72+
6773
for (var i = 0, l = cookies.length; i < l; i++) {
6874
var parts = cookies[i].split('=');
6975
var name = decode(parts.shift());

‎test/tests.js‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -124,20 +124,20 @@ asyncTest('malformed cookie value in IE (#88, #117)', function() {
124124
document.body.appendChild(iframe);
125125
});
126126

127-
test('call without arguments', function() {
127+
test('Call to read all when there are cookies', function() {
128128
$.cookie('c', 'v');
129129
$.cookie('foo', 'bar');
130-
deepEqual($.cookie(), {
131-
c: 'v',
132-
foo: 'bar'
133-
}, 'should return all cookies');
134-
$.each($.cookie(), $.removeCookie);
130+
deepEqual($.cookie(), { c: 'v', foo: 'bar' }, 'returns object containing all cookies');
131+
});
132+
133+
test('Call to read all when there are no cookies at all', function() {
134+
deepEqual($.cookie(), {}, 'returns empty object');
135+
});
135136

137+
test('Call to read all with json: true', function() {
136138
$.cookie.json = true;
137139
$.cookie('c', { foo: 'bar' });
138-
deepEqual($.cookie(), {
139-
c: { foo: 'bar' }
140-
}, 'returns all cookies with JSON parsed');
140+
deepEqual($.cookie(), { c: { foo: 'bar' } }, 'returns JSON parsed cookies');
141141
});
142142

143143

0 commit comments

Comments
 (0)