深入理解 Array.prototype.map()

map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

语法

let new_array = arr.map(function callback(currentValue, index, array) {
// Return element for new_array
}[, thisArg])

参数

  • callback 生成新数组元素的函数,使用三个参数:

    • currentValue 数组中正在处理的当前元素。
    • index 数组中正在处理的当前元素的索引。
    • array map 方法被调用的数组。
  • thisArg 可选的。执行 callback 函数时 使用的this 值。

实际应用

使用指定的方法对数组做批处理

原理

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
console.log(numbers) // [1, 4, 9]
console.log(roots) // [1, 2, 3]

封装

var numbers = [1, 4, 9];
const arrBat = (arr, func) => arr.map(func)
var roots = arrBat(numbers, Math.sqrt)
console.log(numbers) // [1, 4, 9]
console.log(roots) // [1, 2, 3]

只需要传入对应的处理方法,即可对数组所有元素做批处理。

当然也可对此方法进行二次封装:

var numbers = [1, 4, 9];

const arrBat = (arr, func) => arr.map(func)
const arrToSqrt = (arr) => arrBat(arr, Math.sqrt) // 开平方根
const arrToSquare = (arr) => arrBat(arr, e => Math.pow(e, 2)) // 平方
const arrToRound = (arr) => arrBat(arr, Math.round) // 四舍五入
const arrToCeil = (arr) => arrBat(arr, Math.ceil) // 求上整
const arrToFloor = (arr) => arrBat(arr, Math.floor) // 求下整
const arrToDouble = (arr) => arrBat(arr, e => 2 * e) // 求倍数 arrToSquare(numbers) // [1, 16, 81]
arrToSqrt(numbers) // [1, 2, 3]

多参数函数批量转化的误区

先看下面一个方法:

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

第一反应,这里应该返回的是 [1, 2, 3],然而,实际上返回的却是 [1, NaN, NaN]

这是为什么呢?

事实上,parseInt 接收两个参数,第一个是原始值,第二个是进制值,通常我们使用 parseInt('5') 类似的操作,实际上是默认第二参数为 10,。但注意,在 map 回调函数中,有三个参数,第一个是遍历出来的每一个元素,第二参数为遍历出的元素的下标,第三参数为调用者本身。这里, parseInt 接到了 map 的前两个参数,也就是元素和下标,第三参数被忽略,parseInt 把传过来的索引值当成进制数来使用,从而返回了NaN。

正确的做法是:

const arrToInt = str => Array.prototype.map.call(str, e => parseInt(e, 10))
arrToInt("57832") // [5, 7, 8, 3, 2]
arrToInt([1.2, 3.4, 9.6]) // [1, 3, 9]

parseInt 不同,下面的结果会返回浮点数或指数 :

['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]

使用 map 重新格式化数组中的对象

原理

var kvArray = [{key: 1, value: 10}, {key: 2, value: 20}, {key: 3, value: 30}]

var reformattedArray = kvArray.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
// [{1: 10}, {2: 20}, {3: 30}],

封装

var kvArray = [{key: 1, value: 10}, {key: 2, value: 20}, {key: 3, value: 30}]

kvArrayToObjArray = (obj) => obj.map(e => {
var rArr = [];
rArr.push(e.key, e.value);
return rArr;
}) var reformattedArray = kvArrayToObjArray(kvArray)
// [[1, 10], [2, 20], [3, 30]]

反转字符串

原理

var str = 'Hello';
Array.prototype.map.call(str, function(x) {
return x;
}).reverse().join(''); // 'olleH'

封装

const reverseStr = str => Array.prototype.map.call(str, e => e).reverse().join('')
c = reverseStr('Hello') // 'olleH'

当然,还有一个更简单的反转字符串方法,使用 ES6 的解构即可

const reverseString = str => [...str].reverse().join('');

reverseString('foobar') // 'raboof'

将字符串转换为 ASCII 码

原理

var a = Array.prototype.map.call("Hello World", function(x) {
return x.charCodeAt(0);
})
// [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

封装

const strToAscii = str => Array.prototype.map.call(str, e => e.charCodeAt(0))
strToAscii("Hello World") // [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

DOM 操作

甚至可以使用 map 对 DOM 进行操作

var elems = document.querySelectorAll('select option:checked');
var values = Array.prototype.map.call(elems, function(obj) {
return obj.value;
});

深入理解 Array.prototype.map()的更多相关文章

  1. Javascript中Array.prototype.map()详解

    map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数.callback 每次执行后的返回值组合起来形成一个新数组. callback 函数只会在有值的索引上被调用:那些从来没被赋 ...

  2. Array.prototype.map()详解

    今天在地铁上看到这样一个小例子: ["1","2","3"].map(parseInt); 相信很多人和我一样,觉得输出的结果是[1,2,3 ...

  3. js 数组map用法 Array.prototype.map()

    map 这里的map不是"地图"的意思,而是指"映射".[].map(); 基本用法跟forEach方法类似: array.map(callback,[ thi ...

  4. Array.prototype.map()

    mdn上解释的特别详细 概述 map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组. 语法 array.map(callback[, thisArg]) 参数 callb ...

  5. Array.prototype.map()和Array.prototypefilter()

    ES5 => 筛选功能  Array.prototypefilter(): 代码: var words = ['spray', 'limit', 'elite', 'exuberant', 'd ...

  6. javascript的Array.prototype.map()和jQuery的jQuery.map()

    两个方法都可以根据现有数组创建新数组,但在使用过程中发现有些不同之处 以下面这个数据为例: var numbers = [1, 3, 4, 6, 9]; 1. 对undefined和null的处理 a ...

  7. Array.prototype.map()方法详解

    Array.prototype.map() 1 语法 const new_array = arr.map(callback[, thisArg]) 2 简单栗子 let arr = [1, 5, 10 ...

  8. javascript 一些函数的实现 Function.prototype.bind, Array.prototype.map

    * Function.prototype.bind Function.prototype.bind = function() { var self = this, context = [].shift ...

  9. 理解Array.prototype.slice.call(arguments)

    在很多时候经常看到Array.prototype.slice.call()方法,比如Array.prototype.slice.call(arguments),下面讲一下其原理: 1.基本讲解 1.在 ...

随机推荐

  1. Java将list数据导出到Excel——(八)

    Java实体类 package bean; public class Question { private String timu; //题干 private String leixing; //类型 ...

  2. BackBone结合ASP.NET MVC实现页面路由操作

    1. 问题的背景 什么是页面路由操作,就是通过浏览器地址栏的标记来实现页面内部的一些操作,这些操作具有异步性和持久性.应用场景主要有页面操作过程中的添加收藏夹的操作.后退操作等过程中能完全恢复界面. ...

  3. 【C++】获取URL中主机域名

    // ConsoleApplication1.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <windows.h& ...

  4. IAR各个历史版本的下载地址

    http://supp.iar.com/Updates/?product=EWarm 点击进入上述链接,拉到最底部,点击old version即可见到所有的历史版本!!!

  5. 《Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks》

    <Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks> 论文主要的三个贡 ...

  6. sqlserver2008r2实现镜像

    拓扑图 环境 主服务器: 192.168.8.16 winserver2008b 镜像服务器 192.168.11.128 mssql1 见证服务器: 192.168.8.69 server2008c ...

  7. androidpn 推送系统

    (文中部分内容来自网络,如无意中侵犯了版权,请告之!) XMPP协议: XMPP : The Extensible Messaging andPresence Protocol. 中文全称:可扩展通讯 ...

  8. Idea xml 粘贴文本保持原有格式

    setting->Editor->Code Style->XML 在右边的面板中,单击第二个 “Other” 的页签,勾选“Keep white spaces”,重启idea.

  9. ECMAscript5 新增数组内函数

    indexOf() 格式:数组.indexOf(item, start) 功能:从start这个下标开始,查找item在数组中的第一次出现的下标. 参数:item 我们要去查找的元素 start从哪个 ...

  10. 主机可以ping通虚拟机,但是虚拟机ping不通主机的方法(转)

    https://blog.csdn.net/hskw444273663/article/details/81301470