JS foreach function

Source: Internet
Author: User
Tags javascript extension javascript array

Citation: http://www.jb51.net/article/67441.htm

English reference: http://www.tutorialspoint.com/javascript/array_foreach.htm

The ForEach () method of the JavaScript array calls each element in the array.
Grammar

Array.foreach (callback[, Thisobject]);

The following is the details of the parameters:

    • Callback: A function that tests each element in the array. Function to test for each element of an array.
    • Thisobject: Executes the callback function as the object referred to in this. Object to use as this when executing callback.

return value:

Returns the created array.
Compatibility:

This approach is a JavaScript extension to the ECMA-262 standard, so it may not exist in other implementations of the standard. To make it work, you need to add the following script code to the top:

if(!Array.prototype.forEach) {Array.prototype.forEach=function(Fun/*, Thisp*/) {  varLen = This. Length; if(typeofFun! = "function")   Throw NewTypeError (); varThisp = arguments[1];  for(vari = 0; i < Len; i++)  {   if(Iinch  This) Fun.call (Thisp, This[i], I, This); } };}

Example:

if(!Array.prototype.forEach) {Array.prototype.forEach=function(Fun/*, Thisp*/) {  varLen = This. Length; if(typeofFun! = "function")   Throw NewTypeError (); varThisp = arguments[1];  for(vari = 0; i < Len; i++)  {   if(Iinch  This) Fun.call (Thisp, This[i], I, This); } };}functionPRINTBR (element, index, array) {document.write ("<br/>[" + index + "is" +element); }[12, 5, 8, 130, 44].foreach (PRINTBR); </script></body>

This will produce the following results:

[0] is a[1] is 5[2] was 8[3] is[

JS foreach function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.