物体丢失了

时间:2014-12-06 15:52:39

标签: javascript arrays angularjs

在我的角度应用程序中,我正在尝试在页面之间保存/检索数据并具有以下功能:

$scope.storeData = function () {

    var selections = $scope.devices;
    console.log(selections);

    sessionStorage.setItem('selectedHandsets', JSON.stringify(selections));

    var ss = sessionStorage.getItem('selectedHandsets');
    console.log(ss);

}

这个问题很奇怪。我在selections中的关键值是'selectedManufacturer'和'selectedModel',这些值在console.log(selections)中按预期显示。

记录ss时,sessionStorage.selectedHandsets中不会显示“selectedManufacturer”和“selectedModel”。他们在设置数据时就在那里,因为我们可以在选择中看到它,但是当我记录ss时,它们就消失了!

selections的格式如下:

[
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacuterer: { ... }
    ],
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacuterer: { ... }
    ]
]

如果我将JSON.stringify()包裹在console.log(selections)附近,则selectedModel和selectedManufacturer正在消失。有人可以向我解释为什么会发生这种情况以及适当的解决办法是什么?

2 个答案:

答案 0 :(得分:2)

您是否尝试过检查控制台是否会抛出错误?

你所拥有的是一个格式错误的JSON

[
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacuterer: { ... }
    ],
    [
        { ... },
        { ... },
        selectedModel: { ... },
        selectedManufacuterer: { ... }
    ]
]

看看

    [
        { ... },
        { ... },
        selectedModel: { ... }, //There shouldn't be a named item in an array here
        selectedManufacuterer: { ... } //There shouldn't be a named item in an array here
    ]

数组中不应该有命名对象。


EDITS

你做的是这样的:

var arrayBuff= [];
arrayBuff.push(2);
arrayBuff.push(4);
arrayBuff.push(6);

//this would produce this: [2,4,6]
console.log(arrayBuff);

arrayBuff.someField = "foobar";

//this would produce this: [2,4,6, someField: "foobar"]
// which is a malformed array
console.log(arrayBuff);

您可以这样做:

var arrayBuff = {},
    arrayBuff.arrays = [];
arrayBuff.arrays.push(2);
arrayBuff.arrays.push(4);
arrayBuff.arrays.push(6);

//this would produce this: { arrays: [2,4,6] }
console.log(arrayBuff);

arrayBuff.someField = "foobar";

//this would produce this: { arrays: [2,4,6], someField: "foobar"}
// which is correct and can be parsed by JSON.stringify
console.log(arrayBuff);

JSON.stringify无法解析命名字段的原因只是因为它期待一个数组。

答案 1 :(得分:0)

之前的答案是对的。你可以做的是将你的选择重建为一个像这样的对象 {arrObjs:[你的阵列将在这里],型号:[...],制造商:[...]}