Tutorials Point


  JavaScript Basics
  JavaScript Objects
  JavaScript Advanced
  JS Useful References
  JS Useful Resources
  Selected Reading

Copyright © 2014 by tutorialspoint



  Home     References     Discussion Forums     About TP  

Javascript Array every Method


previous next AddThis Social Bookmark Button


Advertisements

Description:

Javascript array every method tests whether all elements in the array pass the test implemented by the provided function.

Syntax:

array.every(callback[, thisObject]);

Here is the detail of parameters:

  • callback : Function to test for each element.

  • thisObject : Object to use as this when executing callback.

Return Value:

Returns true if every element in this array satisfies the provided testing function.

Compatibility:

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work you need to add following code at the top of your script:

if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this &&
          !fun.call(thisp, this[i], i, this))
        return false;
    }

    return true;
  };
}

Example:

<html>
<head>
<title>JavaScript Array every Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this &&
          !fun.call(thisp, this[i], i, this))
        return false;
    }

    return true;
  };
}
function isBigEnough(element, index, array) {
  return (element >= 10);
}

var passed = [12, 5, 8, 130, 44].every(isBigEnough);
document.write("First Test Value : " + passed ); 
  
passed = [12, 54, 18, 130, 44].every(isBigEnough);
document.write("Second Test Value : " + passed ); 
</script>
</body>
</html>

This will produce following result:

First Test Value : falseSecond Test Value : true

To understand it in better way you can Try it yourself.



previous next Printer Friendly

Advertisements


  

Advertisements