所以我正在尝试为我的网络应用程序进行一些前端单元测试。在用户可以添加产品的 View 中,我有以下代码:
var ProductEntry = {Title: ProductTitle, Description: Description, Hashtags: Hashtags,
Picture1: Picture1, Picture2: Picture2, Picture3: Picture3, Start: startdate, ETA:
ETADate}
ProductsArray.push(ProductEntry);
localStorage.setItem("Product", JSON.stringify(ProductsArray));
在我尝试检索数组的 View 中,我的 jQuery 代码是:
$("#SearchButton").click(function(){
var SearchQuery = document.getElementById("SearchField").value;
var storageObject = JSON.parse(localStorage.getItem("Product"));
alert(storageObject[1].Title);
});
上面,我尝试访问 ProductEntry 对象的属性“Title”。我哪里出错了?该项目从 C# MVC 环境切换。
最佳答案
问题是您尝试创建的 ProductEntry 不是有效的 JSON。
试试这个代码:
var ProductEntry = [{Title: 'ProductTitle', Description: 'Description', Hashtags: 'Hashtags',
Picture1: 'Picture1', Picture2: 'Picture2', Picture3: 'Picture3', Start: 'startdate', ETA:
'ETADate'}]
localStorage.setItem("Product", JSON.stringify(ProductEntry));
$("#SearchButton").click(function(){
var SearchQuery = document.getElementById("SearchField").value;
var storageObject = JSON.parse(localStorage.getItem("Product"));
alert(storageObject[0].Title);
});
关于javascript - JSON.parse 返回 [Object object] 寻找访问对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35212837/