jQuery TypeError:数组索引未定义

jQuery TypeError: array index is undefined

本文关键字:索引 未定义 数组 TypeError jQuery      更新时间:2023-09-26

我有一些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

我怎样才能解决这个问题?顺便问一下,有没有优化的方法?

您创建"二维"数组的方式对于此任务不是最佳的。你最好使用一个对象数组,你可以这样创建:

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
    };
});

当你这么做的时候

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);
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++;
        });