D
D
Denis Adamov2020-04-26 23:36:17
JavaScript
Denis Adamov, 2020-04-26 23:36:17

Why is a string returned instead of an array?

Hello, why is a string returned and not an array?

var cart = [
           {id: '1', name: 'gel1', photo: '1.png', price: '1.50'},
           {id: '2', name: 'gel2', photo: '2.png', price: '2.50'},
      ];
        $.cookie('cart',  JSON.stringify(cart));


I created a cookie with a multidimensional array, got it like this and decided to iterate

let cart = $.cookie('cart');
        if (cart != undefined) {
            for (var i = 0; i < cart.length; i++) {
                alert(cart[i]);
            }
        }


But instead of an array, the variable cart contains a string that iterates not by elements, but by characters.
Tried to do so But in this case it does not work at all, since js itself has already reformatted the string. How can I get not a string, but an array?

var cart = JSON.parse($.cookie('name'));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shsv382, 2020-04-26
@shsv382

Maybe because you yourself turn the array into a string with this call?JSON.stringify(cart)

N
no-taktik, 2020-04-27
@no-taktik

const cart = JSON.parse($.cookie('cart'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question