我刚开始使用JSON。我有一个for循环,如下所示,每次执行都返回不同的product
(具有不同的owner_id
和name
字段)
for (/* some condition here */) {
product = {
owner_id: somevalue,
name: somevalue
}
}
我需要存储所有不同出现的product
,以便以后使用。我正在考虑使用数组,所以我将上面的代码改为:
var selectedProducts = [];
for (/* some condition here */) {
product = {
owner_id: somevalue,
name: somevalue
}
selectedProducts.push(product);
selectedProducts.push(JSON.stringify(product));
}
但我得到的是一个包含undefined
内容的数组。
稍后我需要实现的是调用如下那样的for循环
for(var i = 0; i < selectedProducts.length; i++) {
console.log(selectedProducts[i]); // Will print the single JSON object
}
我怎样才能达到这样的结果?
您可以将selectedProducts
数组存储在会话中(请参阅文档)。
var selectedProducts = [];
for (/* some condition here */) {
product = {
owner_id: somevalue,
name: somevalue
}
selectedProducts.push(product);
}
req.session.selectedProducts = selectedProducts;
然后从会话中取回数组。
for(var i = 0; i < req.session.selectedProducts.length; i++) {
console.log(req.session.selectedProducts[i]); // Will print the single JSON object
}