如何根据ForEach定义地图 [英] How to Define Map in Terms of ForEach

查看:65
本文介绍了如何根据ForEach定义地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了自己的map函数,该函数的作用与Array对象上的方法相同. (我这样做是为了学习).代码如下.

I have defined my own map function, which serves the same purpose as the method on Array objects. (I am doing this to learn). The code is below.

我想在我自己的map定义中使用Array的forEach方法,但是从概念上讲我缺少一些东西.我将如何使用forEach做到这一点?

I would like to use Array's forEach method inside of my own definition of map, but I am missing something conceptually. How would I be able to do this using forEach?

无需使用forEach即可工作

// transforming with map
// NOTE: map is already defined in JavaScript
function map(array, transformation) {
  var mapped = [];

  for (var index in array) {
    var currentElement = array[index];
    var transformedElement = transformation(currentElement);
    mapped.push(transformedElement);
  }

  return mapped;
}

我尝试使用forEach

function mapForEach(array, transformation) {
    var mapped = [];

    array.forEach(transformation(currentVal, index, array, mapped));

    return mapped;
}

function transformation(person, index, array, accumulator) {
    var name = person.name;

    accumulator.push(name);
}

推荐答案

您的方法几乎正确,但是就像@ Katana314所说的那样,您需要绑定而不是调用.
这是我的处理方式:

You're almost right with your method, but like @Katana314 says, you need to bind, not call.
Here's how I would do it:

function map(array,mapper) {
    var ret=[];
    array.forEach((val,key)=>{
        //Since arrays are supposed to be sequential, we don't have to worry
        //about keys matching, if they don't match, the user/developer did
        //something horribly wrong.
        ret.push(mapper(val,key,array));
    });
    return ret;
}

这就是我要解决的方法.

And here's how I would fix your way.

function mapForEach(array, func) {
    var mapped = [];
    array.forEach(mapForEachPusher.bind(null,mapped,func));
    return mapped;
}
function mapForEachPusher(mapped,func,value,index,array) {
    mapped.push(func(value,index,array));
}

function extract_name(person) {
    return person.name;
}
mapForEach(
    [{name:'Billy'},{name:'Bob'},{name:'Bridget'},{name:'Brittany'},{name:'"B word"'}]
    ,extract_name
);
//["Billy", "Bob", "Bridget", "Brittany", "\"B word\""]

实际上是同一件事,您可以通过方式将.push()调用移出主函数,这意味着您必须传递数据,而我只需要从外部范围引用即可.我这样做的唯一弊端是该函数的开销,但这是一个箭头函数,因此可能使其轻巧到足以无关紧要.

It's effectively the same thing, your way moves the .push() call out of the main function, which means you have to pass data around, whereas I only need to reference from the outer scope. The only downside to my way is the overhead of the function, but it is an arrow function, so that might make it lightweight enough to not matter.

这篇关于如何根据ForEach定义地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆