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

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

Open
wingmeng opened this issue May 31, 2019 · 0 comments
Open

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

wingmeng opened this issue May 31, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 31, 2019

题目:

请编写一个方法 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant