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
About arrays
What you usually want for iterating over array is the forEach method:
In your specific case for incrementing each element of array, I'd recommend the map method:
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):
But don't use the
for ... in
construct for arrays - this is meant for objects.About references
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:
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:
Here you create a completely new object
11
and assign its reference to variableheight
. But variableh
outside the function still contains the old reference and so remains to point at10
.You can use Array.prototype.find, wich does exactly what you want, returns the first element fullfilling the condition. Example:
Just came across the same problem. Tim Down came close, he just needed a wrapper to the length of the filtered array:
Usage:
I hope that answers this long standing question!