深入理解 Array.prototype.map()
深入理解 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()的更多相关文章
- Javascript中Array.prototype.map()详解
map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数.callback 每次执行后的返回值组合起来形成一个新数组. callback 函数只会在有值的索引上被调用:那些从来没被赋 ...
- Array.prototype.map()详解
今天在地铁上看到这样一个小例子: ["1","2","3"].map(parseInt); 相信很多人和我一样,觉得输出的结果是[1,2,3 ...
- js 数组map用法 Array.prototype.map()
map 这里的map不是"地图"的意思,而是指"映射".[].map(); 基本用法跟forEach方法类似: array.map(callback,[ thi ...
- Array.prototype.map()
mdn上解释的特别详细 概述 map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组. 语法 array.map(callback[, thisArg]) 参数 callb ...
- Array.prototype.map()和Array.prototypefilter()
ES5 => 筛选功能 Array.prototypefilter(): 代码: var words = ['spray', 'limit', 'elite', 'exuberant', 'd ...
- javascript的Array.prototype.map()和jQuery的jQuery.map()
两个方法都可以根据现有数组创建新数组,但在使用过程中发现有些不同之处 以下面这个数据为例: var numbers = [1, 3, 4, 6, 9]; 1. 对undefined和null的处理 a ...
- Array.prototype.map()方法详解
Array.prototype.map() 1 语法 const new_array = arr.map(callback[, thisArg]) 2 简单栗子 let arr = [1, 5, 10 ...
- javascript 一些函数的实现 Function.prototype.bind, Array.prototype.map
* Function.prototype.bind Function.prototype.bind = function() { var self = this, context = [].shift ...
- 理解Array.prototype.slice.call(arguments)
在很多时候经常看到Array.prototype.slice.call()方法,比如Array.prototype.slice.call(arguments),下面讲一下其原理: 1.基本讲解 1.在 ...
随机推荐
- ubuntu14.04 安装 CUDA 7.5 / CUDA 8.0
原文转自:http://blog.csdn.net/masa_fish/article/details/51882183 CUDA7.5和CUDA8.0的安装过程是一毛一样的.所以如果安装CUDA8. ...
- phantomjs 截取twitter的网页(动态生成的页面)
// This example shows how to render pages that perform AJAX calls// upon page load.//// Instead of w ...
- eclipse指定项目编译级别
指定项目编译级别Eclipse→Preferences→Java→Compiler→Compiler compliance level:1.6或其他 或者,
- hdu 4348 To the moon (主席树区间更新)
传送门 题意: 一个长度为n的数组,4种操作 : (1)C l r d:区间[l,r]中的数都加1,同时当前的时间戳加1 . (2)Q l r:查询当前时间戳区间[l,r]中所有数的和 . (3)H ...
- HTTP SIP 认证
HTTP请求报头: Authorization HTTP响应报头: WWW-Authenticate HTTP认证 基于 质询 /回应( challenge/response)的认证模式. ...
- androidpn 推送系统
(文中部分内容来自网络,如无意中侵犯了版权,请告之!) XMPP协议: XMPP : The Extensible Messaging andPresence Protocol. 中文全称:可扩展通讯 ...
- sklearn.model_selection模块
后续补代码 sklearn.model_selection模块的几个方法参数
- windows service 的错误 错误 14001:
1.Windows服务启动时报:“错误 14001:由于应用程序配置不正确,应用程序未能启动.重新安装应用程序可能会纠正这个问题.”的错误. 原因:Windows 服务程序 配置文件中 <a ...
- 轻松读懂MSIL
原文:http://www.cnblogs.com/brookshi/p/5225801.html
- hdu4533 线段树维护分段函数
更新:x1,y1,x2,y2不用long long 会wa.. #include<iostream> #include<cstring> #include<cstdio& ...