Javascript中Array.prototype.map()详解


Posted in Javascript onOctober 22, 2014

在我们日常开发中,操作和转换数组是一件很常见的操作,下面我们来看一个实例:

var desColors = [],

    srcColors = [

        {r: 255, g: 255, b: 255 }, // White

        {r: 128, g: 128, b: 128 }, // Gray

        {r: 0,   g: 0,   b: 0   }  // Black

    ];
for (var i = 0, ilen = srcColors.length; i < ilen; i++) {

    var color = srcColors[i],

        format = function(color) {

            return Math.round(color / 2);

        };
    desColors.push( {

        r: format(color.r),

        g: format(color.g),

        b: format(color.b)

    });

}
// Outputs:

// [

//    {r: 128, g: 128, b: 128 },

//    {r: 64,  g: 64,  b: 64  },

//    {r: 0,   g: 0,   b: 0   }

// ];

console.log(desColors);

从上例可以看出,所有的操作重复率都比较高,如何来优化呢,幸运的是Ecmascript 5给我们提供了一个map方法,我们可以利用它来优化上例:

var srcColors = [

        {r: 255, g: 255, b: 255 }, // White

        {r: 128, g: 128, b: 128 }, // Gray

        {r: 0,   g: 0,   b: 0   }  // Black

    ],

    desColors = srcColors.map(function(val) {

        var format = function(color) {

            return Math.round(color/2);

        };

        return {

            r: format(val.r),

            g: format(val.g),

            b: format(val.b)

        }

    });

// Outputs:

// [

//    {r: 128, g: 128, b: 128 },

//    {r: 64,  g: 64,  b: 64  },

//    {r: 0,   g: 0,   b: 0   }

// ];

console.log(desColors);

从上例看以看出,我们使用map替换掉了for循环部分,从而只需要关心每个元素自身的实现逻辑。关于map方法详情请戳这里。

1.map基本定义:
array.map(callback[, thisArg]);

map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数。callback 每次执行后的返回值组合起来形成一个新数组。 callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。

callback 函数会被自动传入三个参数:数组元素,元素索引,原数组本身。

如果 thisArg 参数有值,则每次 callback 函数被调用的时候,this 都会指向 thisArg 参数上的这个对象。如果省略了 thisArg 参数,或者赋值为 null 或 undefined,则 this 指向全局对象 。

map 不修改调用它的原数组本身(当然可以在 callback 执行时改变原数组)。

当一个数组运行 map 方法时,数组的长度在调用第一次 callback 方法之前就已经确定。在 map 方法整个运行过程中,不管 callback 函数中的操作给原数组是添加还是删除了元素。map 方法都不会知道,如果数组元素增加,则新增加的元素不会被 map 遍历到,如果数组元素减少,则 map 方法还会认为原数组的长度没变,从而导致数组访问越界。如果数组中的元素被改变或删除,则他们被传入 callback 的值是 map 方法遍历到他们那一刻时的值。

2.map实例:

//实例一:字符串上调用map方法

var result = Array.prototype.map.call("Hello world", function(x, index, arr) {

    //String {0: "H", 1: "e", 2: "l", 3: "l", 4: "o", 5: " ", 6: "w", 7: "o", 8: "r", 9: "l", 10: "d", length: 11}

    console.log(arr);

    return x.charCodeAt(0);

});

//Outputs: [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 

console.log(result);

上例演示了在一个String上使用map方法获取字符串中每个字符所对应的 ASCII 码组成的数组。请注意看打印的console.log(arr)打印的结果。

//实例二:下面的操作结果是什么?

var result = ["1", "2", "3"].map(parseInt);

//Outputs: [1, NaN, NaN] 

console.log(result);

也许你会有疑问,为什么不是[1,2,3]呢?我们知道parseInt方法可接收两个参数,第一个参数为需要转换的值,第二个参数为进制数,不了解的可以戳这里。当我们使用map方法的时候,callback函数接收三个参数,而parseInt最多只能接收两个参数,以至于第三个参数被直接舍弃,与此同时,parseInt把传过来的索引值当成进制数来使用.从而返回了NaN。看下面的输出结果:

//Ouputs: 1

console.log(parseInt("1", 0));

//Ouputs: 1

console.log(parseInt("1", undefined));

//Ouputs: NaN

console.log(parseInt("2", 1));

//Ouputs: NaN

console.log(parseInt("3", 2));

后面两个很容易理解,但是前两个为什么返回1呢?为了解释这个问题,我们看看官方的描述:
If radix is undefined or 0 (or absent), JavaScript assumes the following:
a) If the input string begins with “0x” or “0X”, radix is 16 (hexadecimal) and the remainder of the string is parsed.
b) If the input string begins with “0″, radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
c) If the input string begins with any other value, the radix is 10 (decimal).
在第三点中当string为其他值时,进制默认为10。

那么我们如何修改才能使上例正常输出呢?看下例:

var result = ["1", "2", "3"].map(function(val) {

    return parseInt(val, 10);

});

//Outputs: [1, 2, 3] 

console.log(result);

3.map方法的兼容性:
map方法在IE8及以下浏览器不支持,要想兼容老版本的浏览器,可以:

a) Don't use map.b) Use something like es5-shim to make older IE's support map.c) Use the _.map method in Underscore or Lodash for an equivalent utility function.

以上就是对map方法的理解,希望对初学者有所帮助,文中不妥之处,还望斧正!

Javascript 相关文章推荐
音乐播放用的的几个函数
Sep 07 Javascript
window.location.href的用法(动态输出跳转)
Aug 09 Javascript
js图片模糊切换显示特效的方法
Feb 17 Javascript
JavaScript自定义等待wait函数实例分析
Mar 23 Javascript
form表单转Json提交的方法(推荐)
Sep 23 Javascript
AngularJS入门教程之数据绑定用法示例
Nov 01 Javascript
JQuery判断正整数整理小结
Aug 21 jQuery
javascript高级模块化require.js的具体使用方法
Oct 31 Javascript
vue2.0在table中实现全选和反选的示例代码
Nov 04 Javascript
详解js的视频和音频采集
Aug 09 Javascript
mongodb初始化并使用node.js实现mongodb操作封装方法
Apr 02 Javascript
Bootstrap FileInput实现图片上传功能
Jan 28 Javascript
javascript数组详解
Oct 22 #Javascript
Javascript 数组排序详解
Oct 22 #Javascript
Javascript中arguments对象详解
Oct 22 #Javascript
Javascript中的默认参数详解
Oct 22 #Javascript
js style动态设置table高度
Oct 21 #Javascript
js读写json文件实例代码
Oct 21 #Javascript
一个JavaScript防止表单重复提交的实例
Oct 21 #Javascript
You might like
Laravel 5 框架入门(一)
2015/04/09 PHP
Javascript Function对象扩展之延时执行函数
2010/07/06 Javascript
6款经典实用的jQuery小插件及源码(对话框/提示工具等等)
2013/02/04 Javascript
javascript数组的使用
2013/03/28 Javascript
jquery实现盒子下拉效果示例代码
2013/09/12 Javascript
juery框架写的弹窗效果适合新手
2013/11/27 Javascript
刷新页面的几种方法小结(JS,ASP.NET)
2014/01/07 Javascript
BAT及各大互联网公司2014前端笔试面试题--JavaScript篇
2014/10/29 Javascript
JS动态添加iframe的代码
2015/09/14 Javascript
简单了解Backbone.js的Model模型以及View视图的源码
2016/02/14 Javascript
使用Script元素发送JSONP请求的方法
2016/06/12 Javascript
C#微信小程序服务端获取用户解密信息实例代码
2017/03/10 Javascript
node.js中cluster的使用教程
2017/06/09 Javascript
vuex中使用对象展开运算符的示例
2017/09/25 Javascript
angularJS的radio实现单项二选一的使用方法
2018/02/28 Javascript
angularjs1.X 重构controller 的方法小结
2019/08/15 Javascript
[57:47]Fnatic vs Winstrike 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
Python中一些自然语言工具的使用的入门教程
2015/04/13 Python
python修改字典内key对应值的方法
2015/07/11 Python
Python爬虫实现百度图片自动下载
2018/02/04 Python
Python分支语句与循环语句应用实例分析
2019/05/07 Python
利用pandas合并多个excel的方法示例
2019/10/10 Python
浅谈Python中的字符串
2020/06/10 Python
Python获取浏览器窗口句柄过程解析
2020/07/25 Python
Python用K-means聚类算法进行客户分群的实现
2020/08/23 Python
python 输入字符串生成所有有效的IP地址(LeetCode 93号题)
2020/10/15 Python
python邮件中附加文字、html、图片、附件实现方法
2021/01/04 Python
HTML5 progress和meter控件_动力节点Java学院整理
2017/07/06 HTML / CSS
BRASTY捷克:购买香水、化妆品、手袋和手表
2017/07/12 全球购物
巴西购物网站:Onofre Agora
2020/06/08 全球购物
总经理岗位职责
2013/11/09 职场文书
《长江之歌》教学反思
2014/04/17 职场文书
预备党员学习十八届三中全会精神思想汇报
2014/09/13 职场文书
导游词欢迎词
2015/02/02 职场文书
高中军训感想
2015/08/07 职场文书
Win11如何启用启动修复 ? Win11执行启动修复的三种方法
2022/04/08 数码科技