简体   繁体   English

javascript开发人员在什么情况下使用map()方法?

[英]In what cases do javascript developers use the map() method?

I'm learning about the map() method right now and I understand very basic examples. 我现在正在学习map()方法,并且了解非常基本的示例。

var numbers = [2, 4, 6];

var double = numbers.map(function(value) {
    return value * 2;
});

My question is, in what cases do developers use the map() method to help solve problems? 我的问题是,在什么情况下开发人员会使用map()方法来帮助解决问题? Are there some good resources with real world examples? 在现实世界中有一些好的资源实例吗?

Thanks for the help! 谢谢您的帮助!

As @Tushar referred: 正如@Tushar所提到的:

The map() method creates a new array with the results of calling a provided function on every element in this array. map()方法创建一个新数组,并对该数组中的每个元素调用提供的函数。

So it is basically used when you need to apply certain functionality to every single element of an array and get the result back as an array with the new results. 因此,它在需要将某些功能应用于数组的每个单个元素并将结果作为带有新结果的数组返回给您时基本使用。

For example doubling the numbers: 例如,将数字加倍:

var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
  return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]

It basically helps to shorten your code eliminating the need of using for loop. 它基本上可以帮助缩短代码,而无需使用for循环。 But do remember it is used when every element of the array is manipulated because map() generates similar length of array provided. 但是请记住,在操纵数组的每个元素时都会使用它,因为map()会生成提供的相似长度的数组。

For eg.- in the example you provided doubles will have [2, 8, 18]. 例如,在示例中,您提供的双精度数为[2,8,18]。

where 2 correspond to 1. 4 correspond to 8. 9 correspond to 18. 其中2对应于1. 4对应于8。9对应于18。

I recommend you to watch the whole video but your answer is at the 14th minute: 我建议您观看整个视频,但答案是在第14分钟:

Asynchronous JavaScript at Netflix by Matthew Podwysowski at JSConf Budapest 2015 Netflix上的异步JavaScript,作者Matthew Podwysowski在布达佩斯JSConf上2015

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM