用对象字符串化数组
Stringify array with Objects
我的问题是,在使用 JSON.stringify
和 JSON.parse
之后,我无法访问对象的方法。
我有如下内容:
main.js
var items = [];
define(['item'], function (item) {
var main = function () {
$(document).ready(function) {
$("#anyButton").on("click", function() {
items.push(new item());
items[0].myMethod(); //items[0].myMethod() works fine here.
});
});
}();
});
item.js
var item = function () {
var construnctor,
that = {};
constructor = function () {
return that;
};
that.myMethod= function () {
};
return constructor.apply(null, arguments);
};
return itemModule;
现在我想将 main.js 中的项目数组字符串化并存储到 localStorage:
main.js
window.localStorage.setItem("myKey", JSON.stringify(items));
然后解析回来:
var parsedArray = [];
parsedArray = JSON.parse(window.localStorage.getItem("myKey"));
现在的问题是,我无法访问 item.js 中的 myMethod
以下失败:
parsedArray[0].myMethod();
产生:
parsedArray[0].myMethod is not a function.
问题出在哪里?感谢您的帮助。
JSON.stringify只会转换值类型属性、数组和对象。
函数将被省略。
我的问题是,在使用 JSON.stringify
和 JSON.parse
之后,我无法访问对象的方法。
我有如下内容:
main.js
var items = [];
define(['item'], function (item) {
var main = function () {
$(document).ready(function) {
$("#anyButton").on("click", function() {
items.push(new item());
items[0].myMethod(); //items[0].myMethod() works fine here.
});
});
}();
});
item.js
var item = function () {
var construnctor,
that = {};
constructor = function () {
return that;
};
that.myMethod= function () {
};
return constructor.apply(null, arguments);
};
return itemModule;
现在我想将 main.js 中的项目数组字符串化并存储到 localStorage:
main.js
window.localStorage.setItem("myKey", JSON.stringify(items));
然后解析回来:
var parsedArray = [];
parsedArray = JSON.parse(window.localStorage.getItem("myKey"));
现在的问题是,我无法访问 item.js 中的 myMethod
以下失败:
parsedArray[0].myMethod();
产生:
parsedArray[0].myMethod is not a function.
问题出在哪里?感谢您的帮助。
JSON.stringify只会转换值类型属性、数组和对象。
函数将被省略。