Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

this is what I've got and been struggeling for hours. if I alert(i)in the each loop it gives me 1,2,3... but if I want to use as as key for a multidimensional array it is like a string "i"

$(document).ready(function(){
    var positions=[];

    $( ".box" ).each(function(i) {
        //alert(i);
        var elPositions = {};
        elPositions.i = $(this).offset().top;
        positions.push(elPositions);
        //$elPosArray[i] = $(this).offset().top;
        //$(this).html('outer height--> ' + $(this).outerHeight(true));
    });
    console.log(positions);
    //console.log(el);
});

There are Questions and answers to this topic but none of them helped me to get this to work.

I would like to get an array or obj looking something like:

   positions[0]['offset'] = '120';
   positions[0]['height'] = '300';
   positions[1]['offset'] = '420';
   positions[1]['height'] = '180';
   positions[2]['offset'] = '600';
   positions[2]['height'] = '100';
   positions[3]['offset'] = '700';
   positions[3]['height'] = '300';

Here is a fiddle with the html http://jsfiddle.net/Z9WrG/

share|improve this question

1 Answer 1

up vote 2 down vote accepted

You're pretty much there!

In your loop, elPositions (here renamed data) is recreated new on each iteration, and then pushed into the array with a consecutive index. There's no need to specify i in the data object as i is assigned automatically when you push into the array.

See updated fiddle: http://jsfiddle.net/Z9WrG/2/

and code:

$(document).ready(function(){
    var positions=[];

    $( ".box" ).each(function() {
        var $this = $(this);
        var data = {};

        data.offset = $this.offset().top;
        data.height = $this.height();

        positions.push(data);
        // Now, positions[iteration_index] = { offset: x, height: y }
    });

    console.log(positions);
    console.log(positions[0].height);
    console.log(positions[0].offset);
});
share|improve this answer
    
I know, I know, I shouldn't say thanks here. BUT THANKS ZOUGEN :-) awesome, also for telling what I was doing wrong! –  caramba Jan 23 at 15:34
    
You're welcome... no problem! :D –  Zougen Moriver Jan 23 at 15:39
    
@caramba - There is nothing wrong with thanking someone for help in the comments ;) The general stance is don't add thanks at the end of your question so it's as clear and concise as possible. –  webnoob Jan 23 at 17:13
    
@webnoob thank you for that information! –  caramba Jan 24 at 8:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.