The Foreach method of the array of JavaScript arrays

Source: Internet
Author: User

The foreach extension method of the JavaScript arrays array, foreach, is one of the most commonly used array extension methods, equivalent to a parameterized loop array, which simply applies the incoming function on each element of the array, which also means that only the elements that exist are accessed and processed.

If we replace the handler with Console.log, we can get another interesting result: [three-in-a-csser, '].foreach ' (console.log);

Results:

1, 0, array[1, 2, 3, "Csser"]

2, 1, array[1, 2, 3, "Csser"]

3, 2, Array[1, 2, 3, "Csser"]

Csser, 3, Array[1, 2, 3, "Csser"]

Here the foreach function passes 3 arguments each time the console.log is called. Obviously, these 3 parameters are: The current item, the index of the current item, and the array itself,

ForEach is a basic array high order (Higher-order) method whose syntax is defined as: Array.foreach (callback[, Thisobject]) The first parameter we already know, it is a function with 3 parameters, The function is applied to each item of the array.

The second parameter, which represents the context object, or the This value, is used to point to the this reference of the callback function. This can sometimes be useful, for example, when we want to use the method of an object as a handler for the Foreach function:

var database = {users: ["Csser", "John", "David"], sendemail:function (user) {
if (this.isvaliduser (user)) {/* Send message */}}, Isvaliduser:function (user) {/* Verify code */}}; Send a message to each user

Under simple analysis, this point inside the SendMail function points to the database object, and This.isvaliduser points to the required function, if we do not pass in the second argument, the this value will be pointed to the global object by default (window in the browser) or to undefined in strict mode.

The Foreach method of the array of JavaScript arrays

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.