Prototype extension of the JavaScript array Traversal map ()

Source: Internet
Author: User
Tags javascript array

In JavaScript 1.6, JavaScript arrays add several useful methods: IndexOf, LastIndexOf, every, filter, ForEach, map, some, where the first two can be attributed to the element location method, Some of the latter can be categorized as iterative (iterative) methods.

Unfortunately, these new methods are not supported by all browsers, in which case we need to do it ourselves, and in these introductory articles we also provide implementations in browsers that do not support these new features.

The native methods are as follows:

1 varmappedArray = array.map(callback[, thisObject]);
    • Callback: The callback function to execute for each array element.
    • Thisobject: The This object that is defined when the callback function is executed. Venetian Macao Casino

Each element in an array executes one specified function (callback) at a time and creates a new array for the element with the result of each return. It executes the specified function only for non-empty elements in the array, no assignment, or the deleted element is ignored.

The callback function can have three parameters: the current element, the index of the current element, and the current array object. If the parameter thisobject is passed in, it will be treated as the this object inside the callback function (callback), and if it is not passed or null, the global object will be used.

Map does not change the original array, remember: Only the array elements passed in before the callback function executes, the elements that are added after the callback function begins execution are ignored, and when the callback function begins execution to the last element, the array element is deleted or changed, whichever time the callback function accesses the element. , the deleted element is ignored.

If the browser does not support the map method, you can also use prototype to expand it as follows:

01 <script type="text/javascript">
02 //扩展原型对象
03 Array.prototype.map = function(fn){
04     vara = [];
05     for(vari = 0; i < this.length; i++){
06         varvalue = fn(this[i], i);
07         if(value == null){
08             continue//如果函数fn返回null,则从数组中删除该项
09         }
10         a.push(value);
11     }
12     returna;
13 };
14
15 //例子,arr为原始数组
16 vararr = [
17     {name: ‘gonn‘, age: 20, sex: ‘1‘, No: ‘274200‘},
18     {name: ‘nowamagic‘, age: 30, sex: ‘0‘, No: ‘274011‘},
19     {name: ‘frie‘, age: 40, sex: ‘1‘, No: ‘274212‘}
20     ];
21  
22 //使用map更改数组每项的值,可对数组每一项元素内部进行增删改,也可以通过return null来删除数组的某项
23 vararr2 = arr.map(function(item, i){
24     item.sex = item.sex == ‘0‘‘女‘‘男‘;
25     if(item.name == ‘tom‘){
26         returnnull//删除name为tom的项
27     }
28     return{
29         index: i,
30         name: item.name,
31         age: item.age + 30 + i,
32         sex: item.sex
33     };
34 });
35  
36 console.log(arr2);
37 </script>

In the Firefox firebug console output:

1 [
2 Object { index=0, name="gonn", age=50, 更多...},
3 Object { index=1, name="nowamagic", age=61, 更多...},
4 Object { index=2, name="frie", age=72, 更多...}
5 ]

Or, you can extend it in the following ways:

View Source print?
01 if(!Array.prototype.map)
02 {
03     Array.prototype.map = function(fun /*, thisp*/)
04     {
05         varlen = this.length;
06         if(typeoffun != "function")
07             thrownewTypeError();
08  
09         varres = newArray(len);
10         varthisp = arguments[1];
11         for(vari = 0; i < len; i++)
12         {
13             if(i inthis)
14                 res[i] = fun.call(thisp, this[i], i, this);
15         }
16  
17         returnres;
18     };
19 }

Happy Coding.

Prototype extension of the JavaScript array Traversal map ()

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.