views:

54

answers:

3

Hi, I'm learning JavaScript using W3C and I didn't find an answer to this question.

I'm trying to make some manipulations on array elements which fulfill some condition.

Is there a way to do it other than running on the array elements in for loop? Maybe something like (in other languages):

foreach (object t in tArray)
   if (t follows some condition...) t++;

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?

As well, I'll be happy for recommendations on more extensive sites to learn JavaScript from. thanks

+1  A: 

You can use for ... in in JavaScript:

for (var key in array) {
    if (/* some condition */) {
        // ...
    }
}

As of JavaScript 1.6, you can use this, too:

for each (var element in array) {
    // ...
}

These are mainly meant to traverse object properties. You should consider to simply use your for-loop.

EDIT: You could use a JavaScript framework like jQuery to eliminate these cross-browser problems. Give it a try. Its $.each()-method does the job.

elusive
True, these methods work, but they are often recommended against. The reason is that it also enumerates other properties of the array object (and a lot of libraries add such properties) which will produce unpredictable results.
sje397
@sje397: Thats right. I highly recommend jQuery for this. Its [`$.each()`-method](http://api.jquery.com/jQuery.each/) works really nice and provides closures. Since JavaScript has function-scope, this can be really helpful when doing lots of stuff in your loops.
elusive
The actual set of properties enumerated by `for...in` is entirely predictable, although it does vary across browsers. What isn't generally predictable is the iteration order. For iterating over an array, `for...in` is generally a bad idea.
Tim Down
@elusive : It would be quite useless loading a full library in order to iterate over an array :p
Golmote
@Golmote: Most JavaScript applications could benefit from jQuery. I suppose that this are not the only lines of code that exist in this project.
elusive
+3  A: 

In most browsers (not IE) arrays have a filter method, which doesn't do quite what you want but does create you an array of elements of the original array that satisfy a certain condition:

function isGreaterThanFive(x) {
     return x > 5;
}

[1, 10, 4, 6].filter(isGreaterThanFive); // Returns [10, 6]

Mozilla Developer Center has a lot of good JavaScript resources. I'd recommend avoiding w3schools, which has many very poor tutorials.

Tim Down
+1  A: 

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.

Rene Saarsoo