About arrays
What you usually want for iterating over array is the forEach method:
arr.forEach(function(el) {
alert(el);
});
In your specific case for incrementing each element of array, I'd recommend the map method:
arr = arr.map(function(t){ return t+1; });
There are also filter, reduce, and others, which too come in handy.
But like Tim Down already mentioned, these won't work by default in IE. But you can easily add these methods for IE too, like shown in MDC documentation, or actually you can even write simpler versions than the ones in MDC documentation (I don't know why they are so un-JavaScript-y over there):
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(func, scope) {
for (var i = 0, len = this.length; i < len; i++) {
func.call(scope, this[i], i, this);
}
};
}
But don't use the for ... in
construct for arrays - this is meant for objects.
About references
Another thing, sometimes I want to use the element's value and sometimes I want to use it as a reference. What is the syntactical difference?
In JavaScript every variable is in fact a reference to some object. But those references are passed around by value. Let me explain...
You can pass an object to a function that modifies the object and the changes will be seen outside the function:
function incrementHeight(person) {
person.height = person.height + 1;
}
var p = {height: 10);
alert(p.height); // outputs: 10
incrementHeight(p);
alert(p.height); // outputs: 11
Here you modify the value to which the person
reference points to and so the change will be reflected outside the function.
But something like this fails:
function incrementHeight(height) {
height = height + 1;
}
var h = 10;
alert(h); // outputs: 10
incrementHeight(h);
alert(h); // outputs: 10
Here you create a completely new object 11
and assign its reference to variable height
. But variable h
outside the function still contains the old reference and so remains to point at 10
.