本文介绍了map给我们的js编程带来的好处及便利:
1.Map能干什么
map可以实现for循环的功能:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <script> var arr = ['val1', 'val2', 'val3']; for(var i = 0; i < arr.length; i++){ console.log(arr[i]); console.log(i); console.log(arr); } arr.map(function(val, index, array) { console.log(val); console.log(index); console.log(array); }); </script> </body> </html>
这里的好处是,我们可以随意在map里面写函数,这样的话代码可读性会大大提高,如下:
function output(val, index, array) { console.log(val); console.log(index); console.log(array); } arr.map(output);
2.Map的兼容性
ECMAScript 5 标准定义了原生的 map() 方法,所以浏览器兼容性较好。如果你想在 IE 9 之前的版本中使用,就需要引入一个 polyfill 或使用 Underscore、Lodash 之类的库了。
3.map和for哪个快
当然,使用for会比map快点,但是差别不是很大,如果对性能要求没有到极致的地步,这点性能差别可以忽略。
如今,在程序员学习过程中基本都会发现一个叫 map 的函数。在发现 map 函数之前,你可能都会使用 for 循环来处理需要多次执行某一行为的场景。一般情况下,在这个循环过程中都会伴随一些数据变换。
命令式
例如,你团队的销售人员交给你一个很长的电邮地址列表。这些邮箱地址获取的时候并没有经过很好地校验,以至于有些是大写的,有些是小写的,还有一些是大小写混合的。使用 for 循环进行数据处理的代码如下:
var mixedEmails = ['JOHN@ACME.COM', 'Mary@FooBar.com', 'monty@spam.eggs']; function getEmailsInLowercase(emails) { var lowercaseEmails = []; for (var i = 0; i < emails.length; i++) { lowercaseEmails.push(emails[i].toLowerCase()); } return lowercaseEmails; } var validData = getEmailsInLowercase(mixedEmails);
这样的做法是有效的,但却把一个实际上简单常见的操作变得复杂。使用 for 循环的函数牵扯了很多不必要的细节。一些痛点如下:
这是命令式的编程方法。我们似乎在口述给电脑该怎么做这件事。
困惑
为了使之前的代码更加清晰整洁,我们改用 map 函数。在任何 map 函数的说明文档中,我们都会看到诸如 “array”、“each”、“index”之类的词。这表明,我们可以把 map 当做不那么“隆重”的 for 循环使用,事实上也是可行的。现在来修改一下之前的代码:
var mixedEmails = ['JOHN@ACME.COM', 'Mary@FooBar.com', 'monty@spam.eggs']; function getEmailsInLowercase(emails) { var lowercaseEmails = []; emails.map(function(email) { lowercaseEmails.push(email.toLowerCase()); }); return lowercaseEmails; } var validData = getEmailsInLowercase(mixedEmails);
这样写不仅能用,而且代码比使用 for 循环更加清楚。除了代码量更少,我们也不用再告诉程序去记录索引和遍历列表的方向了。
然而,这还不够好。这样写还是命令式的编程。我们还是指挥的太多。实际上我们牵涉了很多不必要的细节,似乎都在领着程序的手走每一步。
声明式
我们需要改变我们关于数据变换的思考方式。我们不需要想着:“电脑啊,我需要你取出列表中第一个元素,然后把它转换成小写,再存储到另一个列表中,最后返回这个列表”。相反,我们应该这样想:“电脑,我这有一个混合了大小写的邮件地址列表,而我需要一个全是小写的邮件地址列表,这是一个能够进行小写转换的函数”。
var mixedEmails = ['JOHN@ACME.COM', 'Mary@FooBar.com', 'monty@spam.eggs']; function downcase(str) { return str.toLowerCase(); } var validData = mixedEmails.map(downcase);
There is no doubt that this way of writing is easier to understand, and this is the essence of programming: telling other people your ideas, this person may be other programmers or you in the future. The above code is saying "valid data is the mailbox list mapped using the lowercase conversion function".
Using advanced ways like this to communicate ideas is a core principle of functional programming, and we do just that. Build complex programs by combining simple parts with a single function that are easy to understand.
This way of writing has some additional benefits. The following table is in no particular order:
Although it is common to pass an anonymous function into the first parameter of map, it is recommended to extract the function and name it appropriately. This can help you record the intention of writing this function, so that other developers can understand the function through the function name without having to analyze the code.
Browser support
The ECMAScript 5 standard defines the native map() method, so browser compatibility is better. If you want to use it in versions before IE 9, you need to introduce a polyfill or use a library such as Underscore or Lodash.
Performance
In most cases, there is no obvious performance gap between map functions and for loops in actual coding. The for loop is slightly faster, but if you are not writing a graphics or physics engine, there is no need to consider this difference. Of course, even so, unless you are sure that these performance improvements will help you, it makes sense to optimize in this way. Not big.
Summary
Breaking logic into single-function methods and applying them to data structures will make your code more accurate, robust, and easy to understand. Our philosophy is to be as general as possible, which helps code reuse. Learning this way of thinking will not only help you improve your Javascript skills, but it can also be reflected in most other programming languages, such as Ruby and Haskell.
So, next time you’re about to use a for loop, think again. Remember, the data you want to process is not necessarily an ordinary array. You can process the object, take out its value, use a function to map it, and finally sort out the result array.
The above is a brief introduction about map instead of loop. I hope it will be helpful to everyone's learning.