1

I keep getting Uncaught TypeError: Cannot set property '0' of undefined, but I can't for my life figure out what is wrong!

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

So what is wrong with this code snippet? I have declared anchor as an array. I've been checking for silly typos for an hour now. The error lies in i. But what is the error?

Edit: I found out what's wrong.

4

5 回答 5

1

尝试返回数组?像这样:

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

var anchor = getAnchors();
于 2013-06-20T07:00:44.423 回答
1

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

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

不过感谢您的回复。

于 2013-06-20T07:08:55.640 回答
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 。

于 2013-06-20T07:01:43.800 回答
1

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

var anchor;
function getAnchors() {
    anchor = $.map($('.anchor'), function(el) { return $(el).offset().left; });
}
于 2013-06-20T07:03:34.100 回答
0

你可以这样做:

var anchors = $('.anchor').map(function() {
  return {
    pos: $(this).offset().left,
    id: this.id
  }
}).get();
于 2013-06-20T07:03:37.133 回答