当前位置: 代码迷 >> JavaScript >> JavaScript1.6新特性系列之forEach(通译)
  详细解决方案

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

热度:585   发布时间:2012-09-10 11:02:32.0
JavaScript1.6新特性系列之forEach(翻译)

JavaScript1.6新特性系列之 forEach?

?

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

?

Method of?Array
Implemented in JavaScript 1.6
ECMAScript Edition ECMAScript 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
?
浏览器兼容性



?
  相关解决方案