Javascript jQuery TypeError:数组索引未定义
我有一些Javascript jQuery TypeError:数组索引未定义,javascript,jquery,arrays,Javascript,Jquery,Arrays,我有一些div,需要将每个div的数据存储在一个数组中。所以我用一个二维数组来存储这些数据,方法如下 this.saveBoardAndNotes = function (board_id, board_name) { var noteList = new Array(new Array()); var self = this; var count = 0; $(".optimal-sticky-notes-sticker-not
div
,需要将每个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]未定义
我怎样才能解决这个问题。顺便问一下,有没有优化的方法?提前感谢。创建“二维”阵列的方式并不适合此任务。您最好使用一个对象数组,可以这样创建:
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++;
});
然而,您真正需要的是使用:
创建“二维”数组的方式对于此任务不是最佳的。您最好使用一个对象数组,可以这样创建:
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++;
});
然而,您真正需要的是使用:
当你这样做的时候
var noteList = new Array(new Array());
您有一个数组。这很好,但不能像使用对象那样设置特性值。而不是
noteList[count]['content'] = content;
你必须这么做
noteList[count]。推送(内容)
如果要推送对象,可以这样做
var myObj = {
'content' : content,
'properties' : properties,
'noteID' : noteID
};
noteList[count].push(myObj);
当你这样做的时候
var noteList = new Array(new Array());
您有一个数组。这很好,但不能像使用对象那样设置特性值。而不是
noteList[count]['content'] = content;
你必须这么做
noteList[count]。推送(内容)
如果要推送对象,可以这样做
var myObj = {
'content' : content,
'properties' : properties,
'noteID' : noteID
};
noteList[count].push(myObj);
我从未见过用JavaScript这样创建二维数组代码>;)。我从未见过用JavaScript这样创建二维数组代码>;)。