对象丢失

objects being lost

本文关键字:对象      更新时间:2023-09-26

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

$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中不可见。设置数据时它们就在那里,因为我们可以在选择中看到它,但是当我ss登录时,它们就消失了!

selections的格式是这样的:

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

如果我JSON.stringify()环绕console.log(selections)那么选择的模型和选择的制造商将消失。有人可以向我解释为什么会发生这种情况以及适当的解决方法是什么吗?

您是否尝试过检查控制台是否引发错误?

您拥有的是格式错误的 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
    ]

数组中不应有命名对象。


编辑

你所做的是这样的:

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无法解析命名字段的原因是,仅仅是因为它需要一个数组。

前面的答案是正确的。您可以做的是将选择重建为类似{ arrObjs : [ 您的阵列将在这里], 型号: [...], 制造商:[...] }