如何将对象数组转换为JSON(并返回)?

Red*_*ite 0 javascript json local-storage

为简单起见,我有一个JavaScript数组car对象如下(一个例子):

var car = {
    "color": "red",
    "fuelType": "diesel"
}
Run Code Online (Sandbox Code Playgroud)

我想将这个对象数组存储在用户的localStorage中,并能够检索和添加/删除它.

这是一些我似乎无法正确的示例代码.

addCar(car);

function getCars() {
    var cars = [];
    if (localStorage['cars']) {
        cars = localStorage['cars'];
    }

    return cars;
}

function addCar(car) {
    var cars = getCars();
    cars.push(car);
    localStorage['cars'] = cars;
}
Run Code Online (Sandbox Code Playgroud)

如何将对象数组转换为JSON(并返回)? localStorage只允许存储字符串.我需要将对象数组转换为JSON格式,但我不确定如何.

Wil*_*ean 6

据我所知,本地存储只支持字符串,因此您必须使用JSON.stringify()JSON.parse()获取数据.