我有一些divs
,需要将每个div
的数据存储在一个数组中。所以我使用二维数组以下列方式存储这些数据。
this.saveBoardAndNotes = function (board_id, board_name) {
var noteList = new Array(new Array());
var self = this;
var count = 0;
$(".optimal-sticky-notes-sticker-note").each(function(){
// Replace plain urls with links and improve html
var note = $(this);
var content = note.find(".textarea").html();
var properties = JSON.stringify(self.getProperties(note));
var noteID = note.attr("id");
noteList[count]['content'] = content;
noteList[count]['properties'] = properties;
noteList[count]['noteID'] = noteID;
count++;
});
但是当我尝试在数组中存储多个div时,我在firebug中得到以下错误
TypeError: noteList[count] is undefined
我该如何解决这个问题。顺便问一下,有没有优化的方法?提前谢谢。
答案 0 :(得分:4)
创建“二维”数组的方式不是此任务的最佳选择。您最好使用可以像这样创建的对象数组:
var noteList = [];
var self = this;
var count = 0;
$(".optimal-sticky-notes-sticker-note").each(function () {
// Replace plain urls with links and improve html
var note = $(this);
var content = note.find(".textarea").html();
var properties = JSON.stringify(self.getProperties(note));
var noteID = note.attr("id");
noteList[count] = {};
noteList[count]['content'] = content;
noteList[count]['properties'] = properties;
noteList[count]['noteID'] = noteID;
count++;
});
但您真正需要的是使用$.fn.map
:
var self = this;
var noteList = $(".optimal-sticky-notes-sticker-note").map(function () {
// Replace plain urls with links and improve html
var note = $(this);
var content = note.find(".textarea").html();
var properties = JSON.stringify(self.getProperties(note));
var noteID = note.attr("id");
return {
content: content,
properties: properties,
noteID: noteID
};
});
答案 1 :(得分:2)
当你这样做时
var noteList = new Array(new Array());
你有一个数组数组。这很好,但是您不能像使用对象那样设置属性值。而不是
noteList[count]['content'] = content;
你必须这样做
noteList[count].push(content)
;
如果您想推送物品,可以
var myObj = {
'content' : content,
'properties' : properties,
'noteID' : noteID
};
noteList[count].push(myObj);
答案 2 :(得分:0)
this.saveBoardAndNotes = function (board_id, board_name) {
var noteList = [];
var self = this;
var count = 0;
$(".optimal-sticky-notes-sticker-note").each(function(){
// Replace plain urls with links and improve html
var note = $(this);
var content = note.find(".textarea").html();
var properties = JSON.stringify(self.getProperties(note));
var noteID = note.attr("id");
noteList[count] = {};
noteList[count]['content'] = content;
noteList[count]['properties'] = properties;
noteList[count]['noteID'] = noteID;
count++;
});