PDA

View Full Version : Simple Array Question

jellyksong
01-30-2011, 04:36 AM
Ok...this is gonna sound very stupid to you guys, but I don't get one part of this code.

function range(upto) {
var result = [];
for (var i = 0; i <= upto; i++)
result[i] = i;
return result;
}
show(range(4));

What does result[i]=i mean?
I know it adds the value of i into the array, but how?
Why couldn't you just write it as result[i] or result[] = i?

wartfink
01-30-2011, 06:04 AM
jellyksong,

In the for loop you initialize the i = 0 (zero). When you put the [] behind a named variable, you create an index. The first value of an index generally has an index value of 0 (zero). So, when you initialize the array (named result), the i in the square bracket says: in the array result, the first index value's value is what is on the right side of the equasion, in this case 0 (because that is the value of i. The next time through the for loop, i is incremented by one (the i++ part of the for loop) and so the second value of the array (now result[1] of the array, remember we started with zero) is assigned the value of i on the right side of the = sign and on and on until i <= upto. The end result is that yo have created an array of numbers starting with the number 0 and continuing 1,2,3,4 etc.

Hope this helps

venegal
01-30-2011, 11:00 AM
What does result[i]=i mean?
I know it adds the value of i into the array, but how?
Why couldn't you just write it as result[i] or result[] = i?

result[i] accesses the ith index of the result array. It evaluates to undefined, because it has not been set yet (but does nothing else).

result[i] = i adds the element i to the result array at the ith index (or overwrites it, if the array already has an entry at the ith index, which, in your case, it doesn't). After you have set it this way, result[i] will evaluate to i.

result[] = i isn't valid Javascript at all; it will give you an error. In PHP, \$result[] = i would be ok, and would be the same as array_push(\$result, i), i.e. it would add i to the array at the index that comes after the highest index that already has an entry. In Javascript, though, the correct syntax for this would be result.push(i).

In your case, you could easily change result[i] = i to result.push(i), because i will always be the next unset index anyway.

result[i] = i can be useful, though, if you want to set an arbitrary range of elements (one that doesn't start at 0), where, for some reason, you want the keys to coincide with the values, for example

function range(start, end) {
var result = [];
for (var i = start; i <= end; i++) {
result[i] = i;
}
return result;
}

It can also be useful if you need the return value of the operation to be i (the return value of result.push(i) won't be i, but the length of the array):

function range(start, end) {
var i = start, result = [];
while((result[i] = i++) < end);
return result;
}

jellyksong
01-30-2011, 09:07 PM
Thank you so much for the explanation :D