JavaScript1.6新特性系列之forEach(翻译)

JavaScript1.6新特性系列之 forEach 

 

总结:数组中的每一项多按照指定的方法执行。

 

Method of Array
Implemented inJavaScript 1.6
ECMAScript EditionECMAScript 5th Edition

 

 

语法

 

array.forEach(callback[,thisArg]);

 

参数

 

  • callback  ---每一项指定的执行方法
  • thisArg   ---当callback方法执行时候的this对象


通用性

     forEach 是加入ECMA-262标准里面的,可能在别的标准里面没有它。下面的代码你可以放在你的脚本前面,它可以支持你使用forEach.


  1. if ( !Array.prototype.forEach ) {  
  2.   
  3.   Array.prototype.forEach = function( callback, thisArg ) {  
  4.   
  5.     var T, k;  
  6.   
  7.     if ( this == null ) {  
  8.       throw new TypeError( " this is null or not defined" );  
  9.     }  
  10.   
  11.     // 1. Let O be the result of calling ToObject passing the |this| value as the argument.  
  12.     var O = Object(this);  
  13.   
  14.     // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".  
  15.     // 3. Let len be ToUint32(lenValue).  
  16.     var len = O.length >>> 0; // Hack to convert O.length to a UInt32  
  17.   
  18.     // 4. If IsCallable(callback) is false, throw a TypeError exception.  
  19.     // See: http://es5.github.com/#x9.11  
  20.     if ( {}.toString.call(callback) != "[object Function]" ) {  
  21.       throw new TypeError( callback + " is not a function" );  
  22.     }  
  23.   
  24.     // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.  
  25.     if ( thisArg ) {  
  26.       T = thisArg;  
  27.     }  
  28.   
  29.     // 6. Let k be 0  
  30.     k = 0;  
  31.   
  32.     // 7. Repeat, while k < len  
  33.     while( k < len ) {  
  34.   
  35.       var kValue;  
  36.   
  37.       // a. Let Pk be ToString(k).  
  38.       //   This is implicit for LHS operands of the in operator  
  39.       // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.  
  40.       //   This step can be combined with c  
  41.       // c. If kPresent is true, then  
  42.       if ( k in O ) {  
  43.   
  44.         // i. Let kValue be the result of calling the Get internal method of O with argument Pk.  
  45.         kValue = O[ k ];  
  46.   
  47.         // ii. Call the Call internal method of callback with T as the this value and  
  48.         // argument list containing kValue, k, and O.  
  49.         callback.call( T, kValue, k, O );  
  50.       }  
  51.       // d. Increase k by 1.  
  52.       k++;  
  53.     }  
  54.     // 8. return undefined  
  55.   };  
  56. }  


 
 
举例

[10,20,30,40].forEach(function(elem,index){
   console.log('index='+index+"&elem="+elem);
});

//输出
index=0&elem=10
index=1&elem=20
index=2&elem=30
index=3&elem=40
 
浏览器兼容性



 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值