A simple implementation of each () method in JavaScript

Source: Internet
Author: User

Each () is used to iterate through each element and make the appropriate processing, the following is a simple implementation:

Method One (direct function call):

The code is as follows Copy Code

function each (OBJ,FN) {
if (!FN) return;
if (obj instanceof array) {//array
var i = 0, len = obj.length;
for (; i<len;i++) {
This in the IF (Fn.call (obj[i],i) = = false)//function points to obj[i],i as an index
Break
}
}else if (typeof obj = = ' object ') {//objects
var j = null;
For (j in obj) {
This in the IF (Fn.call (obj[j],j) = = false)//function points to obj[j],j as the property name
Break
}
}
}

Call Method:

var arry = [1,2,3,4,5,6,7];
var user = {name: ' Read on the Triangle Lake ', site: ' Http://www.111cn.net ', addr: ' Wuhan, Hubei ', _salary: ' 1w ', age:22};
Console.log (' ===function=== ');

Each (arry,function (index) {//output array of the first five digits
if (Index > 4) return false;
Console.log (index+ ' => ' +this);
});

Each (user,function (key) {//Output Public property/Method (a property or method that starts with the Convention "_" is private)
if (!/^_/.test (key)) {
if (typeof this = = ' function ') {
Console.log (key+ ' => function [function] ');
}else{
Console.log (key+ ' => ' +this);
}
}
});

Execution results:

===function===
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
Name => on the Lake Delta
Site => http://www.111cn.net
Addr => Hubei Wuhan
Age => 22
Each => function [function]

Method two (prototype extension):

The code is as follows Copy Code

function _each (FN) {
if (!FN) return;
If (this instanceof array) {//array
var i = 0, len = this.length;
for (; i<len;i++) {
This in the IF (Fn.call (this[i],i) = = false)//function points to obj[i],i as an index
Break
}
}else if (typeof this = = ' object ') {//objects
var j = null;
For (J. This) {
This in the IF (Fn.call (this[j],j) = = false)//function points to obj[j],j as the property name break;
}
}
}

Array.prototype.each = Object.prototype.each =_each;

Call Method:

  code is as follows copy code

Console.log (' ===array.prototype| object.prototype=== ');
Arry.each (function (index) {//output array of the first five digits
if (Index > 4) return false;
Console.log (index+ ' => ' +this);
});
User.each (function (key) {//Output Public property/Method (a property or method that starts with the Convention "_" is private)
if (!/^_/.test (key)) {
if (typeof this = = ' function ') {
Console.log (key+ ' => function [function] ');
}else{
Console.log (key+ ' => ' +this);
}
}
});

Execution results:

===array.prototype| object.prototype===
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
Name => on the Lake Delta
Site => http://www.111cn.net
Addr => Hubei Wuhan
Age => 22
Each => function [function]

And finally, I'm going to give you a little bit of justice. In fact, we can use jquery directly to help us complete, do not need to write so much code, such as

Each process one-dimensional array

The code is as follows Copy Code
var arr1 = ["AAA", "BBB", "CCC"];
$.each (arr1, function (i,val) {
alert (i);
Alert (val);
});
alert (i) outputs the 0,1,2
Alert (val) outputs the AAA,BBB,CCC



Each process two-dimensional array

The code is as follows Copy Code
var arr2 = [[' A ', ' AA ', ' aaa '], [' B ', ' BB ', ' BBB '], [' C ', ' cc ', ' CCC ']]
$.each (arr, function (I, item) {
alert (i);
alert (item);
});

ARR2 is a two-dimensional array, the item is equivalent to taking each of the arrays in the two-dimensional array.
Item[0] Relative to the first value in each one-dimensional array
Alert (i) will output as 0,1,2 because the two-dimensional array contains 3 array elements
Alert (item) will output as [' a ', ' AA ', ' aaa '],[' b ', ' BB ', ' BBB '],[' C ', ' cc ', ' CCC ']

After a slight change to the processing of this two-bit array

  code is as follows copy code
 var arr = [[' A ', ' AA ', ' aaa '], [' B ', ' BB ', ' BBB '], [' C ', ' cc ', ' CCC ']]     
  $.each (arr, functi On (i, item) {     
      $.each (item,function (j,val) {
       alert (j);
        alert (val);
   });
});   

Alert (j) will output as 0,1,2,0,1,2,0,1,2
Alert (val) will output as A,AA,AAA,B,BB,BBB,C,CC,CCC


Each process JSON data, which is more powerful and can loop through each attribute

The code is as follows Copy Code
var obj = {one:1, two:2, three:3};
Each (obj, function (key, Val) {
alert (key);
Alert (val);
});

Here alert (key) will output one two three
Alert (val) outputs the one,1,two,2,three,3
Here's why key is not a number but a property, because the JSON format is a set of unordered attributes-values, since the disorder, how to figure it.
And this val is equivalent to Obj[key]

It's easy to use and jquery is a lot more compatible.

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.