Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

javascript - 在原型上实现映射时加深对回调方法的了解(Increasing understanding of callback method when implementing map on a Prototype)

var s = [23, 65, 98, 5];

Array.prototype.myMap = function (callback) {
  var newArray = []; 
  this.forEach(function (a) {
    return newArray.push(callback(a));
  }); 
  return newArray;
};

var new_s = s.myMap(function (item) {
  return item * 2;
});

myMap is a function we have defined that has a param called callback inside myMap is a forEach that executes a function once on each array element.

(myMap是一个我们定义的函数,在myMap中有一个名为callback的参数, myMap是一个forEachmyMap每个数组元素执行一次函数。)

It's this line I don't understand

(我不明白这是这条线)

return newArray.push(callback(a));

so push() to newArray

(所以push()newArray)

MDN push() : - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

(MDN push()-https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/push)

But push() accepts only one parameter.

(但是push()仅接受一个参数。)

So why do we have .push(callback(a)) why not just .push(a) ?

(那么为什么我们有.push(callback(a))为什么不只是.push(a) ?)

  ask by user1554264 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

But push() accepts only one parameter.

(但是push()仅接受一个参数。)

So why do we have .push(callback(a))

(那么为什么会有.push(callback(a)))

The return value of callback(a) is only one parameter.

(的返回值callback(a) 只有一个参数。)

why not just .push(a)?

(为什么不只是.push(a)?)

The point of mapping is to take an array of data and create a new array where each item is transformed in some way.

(映射的重点是获取一个数据数组并创建一个新数组,其中每个项目都以某种方式进行转换 。)

If you didn't pass a through the callback function, it wouldn't be transformed, and you'd just be making a shallow copy.

(如果您没有通过回调函数传递a ,则该函数将不会被转换,而您只是制作一个浅表副本。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...