Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组map方法模拟实现 #37

Open
conan1992 opened this issue Jun 24, 2020 · 0 comments
Open

数组map方法模拟实现 #37

conan1992 opened this issue Jun 24, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

conan1992 commented Jun 24, 2020

map

map() 方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。
map方法接收两个参数;

  • callback
    生成新数组元素的函数
    然后callback又接收3个可选参数,分别是
    • currentValue
      callback 数组中正在处理的当前元素。
    • index
      数组中正在处理的当前元素的索引。
    • array
      map 方法调用的数组
  • thisArg(可选)
    执行 callback 函数时值被用作this

简单实现

Array.prototype.map2 = function(fn, target){
    var result = new Array();
    var len = this.length;
    for(var i=0;i<len;i++){
        result.push(fn.call(target, this[i], i, this));
    }

    return result;
}

按照源码实现的比较复杂的可以看这个 手写数组的 map 方法

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant