Pages

Javascript Array some() Method

4/7/14

Description:

Javascript array some() method tests whether some element in the array passes the test implemented by the provided function.

Syntax:

array.some(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:

If some element pass the test then it returns true otherwise false.

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.some)
{
  Array.prototype.some = 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 true;
    }

    return false;
  };
}

Example:

<html>
<head>
<title>JavaScript Array some Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.some)
{
  Array.prototype.some = 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 true;
    }

    return false;
  };
}

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

var retval = [2, 5, 8, 1, 4].some(isBigEnough);
document.write("Returned value is : " + retval );

var retval = [12, 5, 8, 1, 4].some(isBigEnough);
document.write("<br />Returned value is : " + retval );
</script>
</body>
</html>
This will produce following result:
Returned value is : false
Returned value is : true 

No comments:

Post a Comment

Related Posts