In-depth analysis of JS array Traversal method (recommended), analysis of js

Source: Internet
Author: User

In-depth analysis of JS array Traversal method (recommended), analysis of js

All the friends who have used Underscore know that it has a perfect API for Array (SET) traversal that can be called. _. each () is one of them. The following is a simple example:

var arr = [1, 2, 3, 4, 5];_.each(arr, function(el) {console.log(el);}); 

The above code will output 1, 2, 3, 4, 5 in sequence. Isn't that interesting? You don't have to write a for loop by traversing an array. The _. each () method is very useful for Traversing arrays, but its internal implementation is not difficult at all. Let's take a look at how to implement _. each. Before that, let's take a look at the _. each () API. _. Each () is generally called as follows:

_. Each (arr, fn, context );

It receives three parameters,

The first is the array to be traversed (in fact, the object is also acceptable, which will be discussed later );

The second is its callback function (This callback function can input three parameters, such as: function (el, I, arr), which are the current element, current index, and original array );

The third is the context to which the callback function is bound, that is, the this value of the callback function fn.

Well, the demand is very clear. Start working!

Let's first implement a simplest _. each (). It cannot modify the context this and receives two parameters. The Code is as follows:

Var _ = {}; // assume that this is underscore. // a simplest _. implementation of the each method _. each = function (arr, fn) {for (var I = 0; I <arr. length; I ++) {fn (arr [I], I, arr) ;}return arr; // returns the original array}

How is it? Is it easy? Just use a for loop and call the callback function continuously. Just a few lines of code can be done. I believe no one can understand it! Let's test whether it works properly:

var arr = [1, 2, 3, 4, 5];_.each(arr, function(el, i, arr) {  console.log(el);}); 

Open it in the browser, and then the console will see the correct output.

This simple code doesn't mean anything at all. Let's look at a more challenging example. For example, the array arr has a sum attribute. We need to sum all elements of the array and store them in sum, as shown below:

Var arr = [1, 2, 3, 4, 5]; arr. sum = 0; // The sum attribute is used to store the sum of array elements _. each (arr, function (el, I, arr) {this. sum + = el ;});

At this time, this is used in the callback function. If this is not bound, this is window by default. this is not what we want. We want it to be bound to the array arr. Call or apply can implement this function. The Code is as follows:

Var _ = {}; // assume that this is underscore. // bind: receives two parameters: fn and context // bind fn to the context. var bind = function (fn, context) {context = context | null; return function (el, I, arr) {fn. call (context, el, I, arr );}}//_. each _. each = function (arr, fn, context) {// call the bind method and bind fn to the context. fn = bind (fn, context); for (var I = 0; I <arr. length; I ++) {fn (arr [I], I, arr) ;}return arr ;}// test case: var arr = [1, 2, 3, 4, 5]; arr. sum = 0; // The sum attribute is used to store the sum of array elements _. each (arr, function (el, I, arr) {this. sum + = el ;}, arr); console. log (arr. sum); // 15

Well, this _. each () is powerful enough to traverse the array and change the context of the callback function by specifying this value. However, we mentioned earlier that Underscore's _. each () can also traverse objects. This implementation is not difficult. You only need to determine whether the first input parameter is an object or an array. If it is an array, it will be traversed as we do, otherwise, if it is an object, use the object's... in loop traversal is enough. If you are interested, try it yourself or check the underscore source code.

Note: Since the ES5 standard, native arrays already have traversal methods such as Array. prototype. forEach and Array. prototype. Map. Native Arrays can be used in projects.

The above is a full description of the array Traversal method (recommended) of JS. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.