← 输入框|github.com|刷新
Skip to content

第 22 期(ECMAScript-原型链 继承):实现 Array map #25

Open

Description

@wingmeng

题目:

请编写一个方法 mapArr,实现与 ES5 规范中数组的 map 方法同样的功能

测试用例:

var data = [1, 2, 3, 4];

var result = data.mapArr(function(it, idx, arr) {
  console.log('当前项', it);
  console.log('当前索引', idx);
  console.log('数组', arr);

  return it * 2;
});

console.log(result);  // [2, 4, 6, 8]

参考答案:

Array.prototype.mapArr = function(fn, context) {
  var arr = Array.prototype.slice.call(this);
  var mappedArr = [];

  for (var i = 0; i < arr.length; i++) {
    mappedArr.push(fn.call(context, arr[i], i, this));
  }

  return mappedArr;
}

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions