The difference between each () and foreach () in Javascript/jquery

Source: Internet
Author: User

The two methods seem to have something to do with the name, but the difference between them is quite large in JavaScript.

foreach () is used for the operation of an array, which executes the established function for each element in an array (not arrays cannot use the foreach () method). and $.each () is a method in jquery that executes the function that is developed for each matching element in the collection. In addition, they correspond to the same parameters in the callback function: Array.foreach (ITEM,INDEX,ARRAY1); $ (selector). each (function (index,element)).

Here is the $.each () Example:

      var lst = $ (". Distance");      $ (LST). each (fun);       function Fun (index,item) {          alert (a). Text ());      }
      var arr = [1, 2];      $ (ARR). each (fun);       function Fun (index,item) {          alert (item);      }

The following is an example of a foreach ():

      var arr = [1, 2];      Arr.foreach (fun);       function Fun (num) {          alert (num);      }

So where you use foreach, you can use $.each instead. You can also use the most basic for loop for the operation of the elements in the collection.

The difference between each () and foreach () in Javascript/jquery

Related Article

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.