标签:http   io   使用   ar   java   for   sp   div   on   
在 JavaScript 1.6 里,javascript 数组增加了几个非常有用的方法:indexOf、lastIndexOf、every、 filter、 forEach、 map、 some,其中前两个可以归为元素定位方法,而后面的几个则可以归为迭代(iterative)方法。
遗憾的是:这些新方法并非所有浏览器都支持,在这种情况下,我们就需要自己动手了,在这些介绍的文章中,我们同时提供了在不支持这些新特性的浏览器中的实现方法。
原生方法如下:
| 1 | varmappedArray = array.map(callback[, thisObject]); | 
 
 
 
- callback: 要对每个数组元素执行的回调函数。
- thisObject : 在执行回调函数时定义的this对象。澳门威尼斯人赌场
对数组中的每个元素都执行一次指定的函数(callback),并且以每次返回的结果为元素创建一个新数组。它只对数组中的非空元素执行指定的函数,没有赋值或者已经删除的元素将被忽略。
回调函数可以有三个参数:当前元素,当前元素的索引和当前的数组对象。如参数 thisObject 被传递进来,它将被当做回调函数(callback)内部的 this 对象,如果没有传递或者为null,那么将会使用全局对象。
map 不会改变原有数组,记住:只有在回调函数执行前传入的数组元素才有效,在回调函数开始执行后才添加的元素将被忽略,而在回调函数开始执行到最后一个元素这一期间,数组元素被删除或者被更改的,将以回调函数访问到该元素的时间为准,被删除的元素将被忽略。
如果浏览器不支持map方法,也可以按照下面的方式用prototype去扩展:
| 01 | <script type="text/javascript"> | 
 
| 03 | Array.prototype.map = function(fn){ | 
 
| 05 |     for(vari = 0; i < this.length; i++){ | 
 
| 06 |         varvalue = fn(this[i], i); | 
 
| 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‘} | 
 
| 23 | vararr2 = arr.map(function(item, i){ | 
 
| 24 |     item.sex = item.sex == ‘0‘? ‘女‘: ‘男‘; | 
 
| 25 |     if(item.name == ‘tom‘){ | 
 
| 31 |         age: item.age + 30 + i, | 
 
 
 
在Firefox firebug控制台输出:
| 2 | Object { index=0, name="gonn", age=50, 更多...}, | 
 
| 3 | Object { index=1, name="nowamagic", age=61, 更多...}, | 
 
| 4 | Object { index=2, name="frie", age=72, 更多...} | 
 
 
 
或者以下方式扩展也可以:
| 01 | if(!Array.prototype.map) | 
 
| 03 |     Array.prototype.map = function(fun ) | 
 
| 05 |         varlen = this.length; | 
 
| 06 |         if(typeoffun != "function") | 
 
| 07 |             thrownewTypeError(); | 
 
| 09 |         varres = newArray(len); | 
 
| 10 |         varthisp = arguments[1]; | 
 
| 11 |         for(vari = 0; i < len; i++) | 
 
| 14 |                 res[i] = fun.call(thisp, this[i], i, this); | 
 
 
 
Happy Coding.
JavaScript数组遍历map()的原型扩展
标签:http   io   使用   ar   java   for   sp   div   on   
原文地址:http://www.cnblogs.com/laoyangman/p/3995587.html