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
Use ES6
Array.filter()
and arrow functions with expression body:A bit more concise than @Beauty's answer.
Problem:
I need to know if a client set exists for any PJ client.
Solution:
It's return boolean
Here a short way to write a filter. From an array of numbers it returns all values greater than 5.
Usage example:
And here a filter for an array of objects, which checks a property condition.
Usage example:
Write a generic function that accepts various conditions:
Example:
Usage:
return only elements containing .log extension:
[ 'gogo.log' ]
return only elements containing .png extension:
[ 'hello.png', 'hoho.png' ]
return only elements NOT containing .png extension:
[ 'hello', 'go_there', 'now', 'go_here', 'gogo.log' ]
return elements containing set of extensions and prefixes:
[ 'go_there', 'go_here', 'hello.png', 'gogo.log', 'hoho.png' ]
You can easily pass MULTIPLE CONDITIONS
return all png files that are less than 9 characters long:
[ 'hoho.png' ]
You can use
for ... in
in JavaScript:As of JavaScript 1.6, you can use this, too:
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.In most browsers (not IE <= 8) 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:Mozilla Developer Network has a lot of good JavaScript resources.