Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript/jQuery anonymous functions to populate an array

Hi I was just wondering if building an array in javascript was possible using a function like so. I have a variable that is getting the margins of a series of elements using $(ele).css('margin');. This returns a string of 0px 0px 0px 0px where I only want the left property to check whether it's been animated -= left.

I can do a similar function but I know there must be a better way. Here's my example:

var marginsLeft = new array();
$(ele).each(function(i){
    var r = $(i).css('margin').split(" ");
    marginsLeft[i]=r[3];
});

I'm not entirely sure how to simplify this, but I'm sure it's possible :) thanks in advance.

like image 336
bashleigh Avatar asked Dec 20 '22 11:12

bashleigh


2 Answers

You can use $.map:

var marginsLeft = $(ele).map(function() { 
    return parseInt($(this).css('margin-left'), 10);
}).get();

Update: as pointed out by @undefined, if you want a regular array you should also call .get on the result. Otherwise, you'll have a jQuery wrapped array. It is array-like, so it can be used as an array in many contexts, but not in others (in particular, it may not have the native Array methods).

Also, to convert the result to a number you can use parseInt (which will ignore the letters and use only the digits), remembering to explicitate the base (10).

like image 72
mgibsonbr Avatar answered Jan 17 '23 18:01

mgibsonbr


Have a look at the docs for .each(): The first parameter of the callback function is the index, the array element (DOM node) can be accessed either as the second parameter or the this value. So, use

var marginsLeft = []; // literal shortcut for "new Array()"
$(ele).each(function(i, el){
    marginsLeft[i] = $(el).css('margin-left');
});

You also might have a look at the .map() method, but that returns a jQuery wrapper object instead of an array.

like image 43
Bergi Avatar answered Jan 17 '23 18:01

Bergi