javascript - 实现forEach的问题?
高洛峰
高洛峰 2017-04-10 15:18:08
[JavaScript讨论组]

这是我写的,要实现的就是对数组中的非稀疏元素进行操作

Array.prototype.foreach = function(callback){
  var a = this;
  for(var i = 0;i<this.length;i++){
  if(!(i in a)) continue;
  callback(a[i],i,a);
}
}

这是ES5源码

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18    
  Array.prototype.forEach = function(callback, thisArg) {

    var T, k;

    if (this == null) {    //难道Array可能为null??什么情况下?
      throw new TypeError(' this is null or not defined');
    }

    var O = Object(this);    //这有什么用?

    var len = O.length >>> 0;    //这有什么用?

    if (typeof callback !== "function") {
      throw new TypeError(callback + ' is not a function');
    }

    if (arguments.length > 1) {
      T = thisArg;    //thisArg有什么用?
    }

    k = 0;

    while (k < len) {
      var kValue;    
      if (k in O) {          
        kValue = O[k];  
        callback.call(T, kValue, k, O); 
      }          
      k++;
    }

  };

问题已写在注释中,求指导。


关于第三个问:length >>> 0 ,提供一个参考链接

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
ringa_lee

简单说下
第一个疑问:如果我这样呢[].forEach.call(null, function() {})
第二个疑问:强制转换为Object,为了统一处理循环不报错,也可以处理类似[].forEach.call("123", function() {})
第三个疑问:你可以理解为把length转换为数字,如果length是字符串,也可以转换为数字
第四个疑问,如楼上所说,为了改变callback的this

黄舟

自己的一点见解:

if (this == null) {

用来判断作用对象是否为null 或 undefined , 这里用了 双等 , 作用是在比较之前会默认进行类型转换,比如把 '',undefined,0,false 都给转转化成undefined , 作用是判断、过滤作用对象。

 var target = '' || false || 0 || undefined || null ;
 if(target == null) {
    console.log('target is undefined')
 }

T = thisArg;

这个东西在MDN里有说,他是在forEach执行callback时的this值,比如:
 var array = [1,2,3];
 var result = [];
 array.forEach(function(i){
     this.push(i*i);
 },result);  // result ==> [1, 4, 9]

 或者在reduce里,

 [1,2,3].reduce(
     function(p,v){
         return p + v
     })   // 6

 [1,2,3].reduce(
     function(p,v){
         return p + v
     },10)   // 16
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号