Array.prototype.map()

This article is in need of a technical review.

Summary

Creates a new array with the results of calling a provided function on every element in this array.

Method of Array
Implemented in JavaScript 1.6
ECMAScript Edition ECMAScript 5th Edition

Syntax

array.map(callback[, thisArg])

Parameters

callback
Function that produces an element of the new Array from an element of the current one.
thisArg
Object to use as this when executing callback.

Description

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

If a thisArg parameter is provided to map, it will be used as the this for each invocation of the callback. If it is not provided, or is null, the global object associated with callback is used instead.

map does not mutate the array on which it is called.

The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited.

Compatibility

map is a recent addition to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object, TypeError, and Array have their original values and that callback.call evaluates to the original value of Function.prototype.call.

// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.com/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(callback, thisArg) { var T, A, k; if (this == null) {
throw new TypeError(" this is null or not defined");
} // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
} // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (thisArg) {
T = thisArg;
} // 6. Let A be a new array created as if by the expression new Array(len) where Array is
// the standard built-in constructor with that name and len is the value of len.
A = new Array(len); // 7. Let k be 0
k = 0; // 8. Repeat, while k < len
while(k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[ k ]; // ii. Let mappedValue be the result of calling the Call internal method of callback
// with T as the this value and argument list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
// and false. // In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true }); // For best browser support, use the following:
A[ k ] = mappedValue;
}
// d. Increase k by 1.
k++;
} // 9. return A
return A;
};
}

Examples

Example: Pluralizing the words (strings) in an array

The following code creates an array of "plural" forms of nouns from an array of their singular forms.

function fuzzyPlural(single) {
var result = single.replace(/o/g, 'e');
if( single === 'kangaroo'){
result += 'se';
}
return result;
} var words = ["foot", "goose", "moose", "kangaroo"];
console.log(words.map(fuzzyPlural)); // ["feet", "geese", "meese", "kangareese"]

Example: Mapping an array of numbers to an array of square roots

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
/* roots is now [1, 2, 3], numbers is still [1, 4, 9] */

Example: using map generically

This example shows how to use map on a string to get an array of bytes in the ASCII encoding representing the character values:

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

Tricky use case

(inspired by this blog post)

It is common to use the callback with one argument (the element being traversed). Some functions are also commonly used with one argument. These habits may lead to confusing behaviors.

// Consider:
["1", "2", "3"].map(parseInt);
// While one could expect [1, 2, 3]
// The actual result is [1, NaN, NaN] // parseInt is often used with one argument, but takes two. The second being the radix
// To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array
// The third argument is ignored by parseInt, but not the second one, hence the possible confusion.
// See the blog post for more details /*
function returnInt(element){
return parseInt(element,10);
} ["1", "2", "3"].map(returnInt);
// Actual result is an array of numbers (as expected)
*/

Browser compatibility

JavaScript Array.map的更多相关文章

  1. JavaScript Array -->map()、filter()、reduce()、forEach()函数的使用

    题目: 1.得到 3000 到 3500 之内工资的人. 2.增加一个年龄的字段,并且计算其年龄. 3.打印出每个人的所在城市 4.计算所有人的工资的总和. 测试数据: function getDat ...

  2. JavaScript Array map() 方法

    语法: array.map(function(currentValue,index,arr), thisValue) currentValue:必须.当前元素的值index:可选.当期元素的索引值ar ...

  3. JavaScript Array.map + parseInt

    map 生成新数组的函数,3个参数 1-currentValue, callback数组中正在处理的当前元素 2-index(可选): callback数组中正在处理的当前元素的索引 3-array( ...

  4. JavaScript 对象Array,Map,Set使用

    for(int i = 0 :i < 3 ;i++ ){ //[重点说三遍] 在说明每个对象的用法之前,首先说明 JavaScript 对象的使用一定要注意浏览器的兼容性问题!尤其是IE的版本! ...

  5. JavaScript Array 常用函数整理

    按字母顺序整理 索引 Array.prototype.concat() Array.prototype.filter() Array.prototype.indexOf() Array.prototy ...

  6. JavaScript Array 对象

    JavaScript Array 对象 Array 对象 Array 对象用于在变量中存储多个值: var cars = ["Saab", "Volvo", & ...

  7. [Javascript ] Array methods in depth - sort

    Sort can automatically arrange items in an array. In this lesson we look at the basics including how ...

  8. JavaScript之Map对象

    前言 工欲善其事,必先利其器.这是一款以前在前端项目中没有使用过的.有趣的对象,咱来看看如何使用~ 并非arrayObj.map(function) //arrayObj.map与arrayObj.f ...

  9. 如何实现JavaScript的Map和Filter函数?

    译者按: 鲁迅曾经说过,学习JavaScript最好方式莫过于敲代码了! 原文: Master Map & Filter, Javascript’s Most Powerful Array F ...

随机推荐

  1. java: InputStreamReader将字节的输入流变成字符的输入流,OutputStreamWriter将字符的输出流变成字节的输出流

    InputStreamReader:将字节的输入流变成字符的输入流, OutputStreamWriter:将字符的输出流变成字节的输出流 //将缓冲区的内容读取,可以一次读取 //可以接收键盘的输入 ...

  2. 命令——WPF学习之深入浅出

    WPF学习之深入浅出话命令   WPF为我们准备了完善的命令系统,你可能会问:“有了路由事件为什么还需要命令系统呢?”.事件的作用是发布.传播一些消息,消息传达到了接收者,事件的指令也就算完成了,至于 ...

  3. 深度学习—BN的理解(一)

    0.问题 机器学习领域有个很重要的假设:IID独立同分布假设,就是假设训练数据和测试数据是满足相同分布的,这是通过训练数据获得的模型能够在测试集获得好的效果的一个基本保障.那BatchNorm的作用是 ...

  4. js中scrollIntoView()的用法

    一. 什么是scrollIntoView scrollIntoView是一个与页面(容器)滚动相关的API 二. 如何调用 element.scrollIntoView() 参数默认为true 参数为 ...

  5. toggle input radio

    $(function(){ $('input[name="rad"]').click(function(){ var $radio = $(this); // if this wa ...

  6. 第三方开源--Android Image Cropper--图片裁剪

    github下载地址:https://github.com/ArthurHub/Android-Image-Cropper 有两种使用方式: 第一种:Activity用法 1.添加 CropImage ...

  7. 删除文件夹里的 .svn,

    删除文件夹里的 .svn,cmd  进入相应目录  运行    for /r ./ %a in (./) do @if exist "%a/.svn" rd /s /q " ...

  8. UVA 11291 Smeech

    [来源]https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  9. 在Windows 7上安装ACE 6.1.0

    主机环境    操作系统:Windows 7 专业版准备ACE    用浏览器打开http://download.dre.vanderbilt.edu/,下载ACE-6.1.0和ACE-html-6. ...

  10. 浅谈FFT(快速傅里叶变换)

    本文主要简单写写自己在算法竞赛中学习FFT的经历以及一些自己的理解和想法. FFT的介绍以及入门就不赘述了,网上有许多相关的资料,入门的话推荐这篇博客:FFT(最详细最通俗的入门手册),里面介绍得很详 ...