May 09, 2021 CoffeeScript
You want to be able to detect each element in the array under certain circumstances.
Using Aray.every (ECMAScript 5):
evens = (x for x in [0..10] by 2)
evens.every (x)-> x % 2 == 0
# => true
Array.every was added to Mozilla's Javascript 1.6, ECMAScript 5 standard. I f your browser supports it, but still can't implement EC5, check the .all from underscore .js (http://documentcloud.github.io/underscore/).
For a real example, suppose you have a multi-choice list, as follows:
<select multiple id="my-select-list">
<option>1</option>
<option>2</option>
<option>Red Car</option>
<option>Blue Car</option>
</select>
Now you want to verify that the user has selected only the numbers. Let's take advantage of array.every :
validateNumeric = (item)->
parseFloat(item) == parseInt(item) && !isNaN(item)
values = $("#my-select-list").val()
values.every validateNumeric
This is similar to the array #all in Ruby.