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.

Community
  • 1
  • 1
AKG
  • 2,936
  • 5
  • 27
  • 36

5 Answers5

1

Try returning the array instead? Like this:

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

var anchor = getAnchors();
Kristoffer K
  • 2,053
  • 18
  • 23
1

You need to create the object property before you assign a value to it.

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

then make the assignment and overwrite null with your values.

James LeClair
  • 1,234
  • 10
  • 12
1

You can use $.map to build arrays :

var anchor;
function getAnchors() {
    anchor = $.map($('.anchor'), function(el) { return $(el).offset().left; });
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

I found the answer. I just had to declare anchor in the function instead.

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

Thanks for the replies though.

AKG
  • 2,936
  • 5
  • 27
  • 36
0

You can do this:

var anchors = $('.anchor').map(function() {
  return {
    pos: $(this).offset().left,
    id: this.id
  }
}).get();
elclanrs
  • 92,861
  • 21
  • 134
  • 171