首页 新闻 会员 周边

如何查看 JavaScript 源代码?

0
悬赏园豆:5 [已解决问题] 解决于 2018-01-29 12:11

在下初入博客园不久,菜鸟一枚,提的问题可能在各位大牛看来So easy,见笑了,下面是问题:


今天偶然间在看js的Array,看到Array.filter()的使用,突然想到一个问题,这个filter的源码是这样写的?(其实就是想知道怎样给Array扩展一个和filter类似的方法

filter(callback[,thisArg]),callback有三个参数,分别是 element,index,array

这个callback是怎样定义的?

function myfliter(elem,index){
  return elem>10;
}
为什么传 myfliter 到 filter, myfliter的第一个参数elem就是calback的第一个参数element?并且是Array的当前元素?

PS:请大家不吝赐教。

DevenLiu的主页 DevenLiu | 初学一级 | 园豆:25
提问于:2017-10-20 15:40
< >
分享
最佳答案
0
if (!Array.prototype.filter)
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
        throw new TypeError();
    
    var len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;
    if (thisArg === undefined)
      while (++i !== len)
        // checks to see if the key was set
        if (i in this)
          if (func(t[i], i, t))
            res[c++] = t[i];
    else
      while (++i !== len)
        // checks to see if the key was set
        if (i in this)
          if (func.call(thisArg, t[i], i, t))
            res[c++] = t[i];
    
    res.length = c; // shrink down array to proper size
    return res;
  };
收获园豆:5
写代码的小2B | 老鸟四级 |园豆:4371 | 2017-10-20 15:56

谢谢,这正是我想要的,您已经很好的帮了我。

另外,请问您是如何查看源码的呢?

DevenLiu | 园豆:25 (初学一级) | 2017-10-25 14:21

@L-d-h: 

我是Google来的。

写代码的小2B | 园豆:4371 (老鸟四级) | 2017-10-25 14:25
其他回答(2)
0

看它干啥,知道方法效果就得了。好吧,我不知道。

jasondyoung | 园豆:424 (菜鸟二级) | 2017-10-20 15:45
0

楼上已经帮你贴出源代码了。

简单说就是:filter函数内会对数组进行遍历,每次遍历到一个元素时,会调用myfilter函数。

西漠以西 | 园豆:1675 (小虾三级) | 2017-10-23 17:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册