未捕获的TypeError:无法设置未定义的属性“0”

时间:2013-06-20 06:56:07

标签: javascript jquery loops each

我一直在Uncaught TypeError: Cannot set property '0' of undefined,但我不能为我的生活弄清楚出了什么问题!

var anchor = [];
getAnchors();
function getAnchors() {
    $('.anchor').each(function(i) {
        anchor[i] = $(this).offset().left;
    });
}

这个代码片段有什么问题? 我已将anchor声明为数组。 我一直在检查一段时间的愚蠢错别字。 错误在于i。但 错误是什么?

修改 I found out what's wrong.

5 个答案:

答案 0 :(得分:1)

尝试返回数组?像这样:

function getAnchors() {
    var allAnchors = [];
    $('.anchor').each(function(i) {
        allAnchors.push($(this).offset().left);
    });
    return allAnchors;
}

var anchor = getAnchors();

答案 1 :(得分:1)

您需要在为其指定值之前创建对象属性。

    var anchor = [];
    $('.anchor').each(function(i) {
        anchor[i] = [{
            pos: null,
            id: null
        }];
        anchor[i]['pos'] = $(this).offset().left;
        anchor[i]['id'] = $(this).attr('id');
    });

然后进行赋值并用您的值覆盖null。

答案 2 :(得分:1)

您可以使用$.map构建数组:

var anchor;
function getAnchors() {
    anchor = $.map($('.anchor'), function(el) { return $(el).offset().left; });
}

答案 3 :(得分:1)

我找到了答案。我只需要在函数中声明anchor

getAnchors();
function getAnchors() {
    var anchor = [];
    $('.anchor').each(function(i) {
        anchor[i] = $(this).offset().left;
    });
    // perhaps sort anchor
    console.log(anchor);
}

感谢您的回复。

答案 4 :(得分:0)

你可以这样做:

var anchors = $('.anchor').map(function() {
  return {
    pos: $(this).offset().left,
    id: this.id
  }
}).get();