views:

58

answers:

3

I have a JavaScript array that can be built using this code

var Test = [];
Test.push([3, 2]);
Test.push([5, 7]);
Test.push([8, 1]);
Test.push([4, 10]);

What I need to do is change the first value in each item to be in order from 0, the result should look like this:

[0, 2]
[1, 7]
[2, 1]
[3, 10]

I will also accept a jQuery answer.

+2  A: 
for (var i=0, l=Test.length; i<l; i++){
    Test[i][0] = i;
}
Roland Bouman
+1  A: 
for (var i=0; i < Test.length; i++) {
    Test[i][0] = i;
}
darkporter
+2  A: 

If you want a jquery-ic answer:

  $(Test).each(function(i) {
        this[0] = i;
    });

The thing I like about this approach is that the each method creates a separate function scope for each loop iteration. Though it is not necessary in this example, it can help reduce headaches caused by unintended variable binding.

INCORRECT - Though works

 $(Test).each(function(i) {
        this[0] = i++;
    });
sberry2A
mm, should't `i` be initialized to `0` somewhere?
Roland Bouman
Actually, no. I accidentally left the ++ on the i. The first argument to the each callback is the index (in the case of an array, or the key in the case of an object). Thanks for catching this though.
sberry2A
Neat, didn't know `each` it worked like that. Thanks for the explanation
Roland Bouman