The map method of JS

Source: Internet
Author: User
Tags square root

map()Method creates a new array with the result that each element in the array invokes a supplied function and returns the result.

Let numbers = [1, 5, ten, 2= Numbers.map ((x) + =   {return x *;}); // Doubles is now [2, ten , +] // numbers is still [1, 5, ten, A]  = [1, 4, 9= numbers.map (math.sqrt); // roots is now [1, 2, 3] // numbers is still [1, 4, 9]

syntax Edit
1 Let array = Arr.map (function2     //3 }[, Thisarg])

parameter Edit
callback
A function that generates a new array element, using three parameters:
currentValue
callbackThe first parameter of the array in which the current element is being processed.
index
callbackThe second parameter, the index of the current element being processed in the array.
array
callbackThe third argument, the map method is called by the array.
thisArg
Optional. callbackthe value to use when executing the function this .
return value

A new array, with each element being the result of a callback function.

description Edit

mapMethod invokes the function sequentially for each element in the original array callbackcallbackthe return value (including) after each execution is undefined combined to form a new array. The callback function is called only on the indexed index, and those indexes that have never been assigned a value or are used delete for deletion are not called.

callbackThe function is automatically passed in three parameters: the array element, the element index, the original array itself.

If the thisArg parameter has a value, each time the callback function is called, this it points to the thisArg object on the parameter. If omitted thisArg  参数, 或者赋值为 null or undefined , this is a pointer to the global object.

map Does not modify the original array that invokes it (it can, of course, callback change the original array at execution time).

When working with arrays using the map method, the range of array elements is determined before the first invocation of the callback method. During the execution of the map method: The newly added elements in the original array will not be accessed by callback, and if the existing elements are changed or deleted, their values passed to callback are the values of the time the map method traverses them, and the deleted elements will not be accessed.

example Edit To find the square root of each element in the array

The following code creates a new array with a value of the square root of the corresponding number in the original array.

1 var numbers = [1, 4, 9]; 2 var roots = Numbers.map (math.sqrt); 3 // The value of roots is [1, 2, 3], and the value of numbers is still [1, 4, 9]

Reformat an object in an array using map

The following code creates an array containing objects to create a new array containing the newly reformatted object.

1 varKvarray = [{key:1, value:10}, 2{key:2, value:20}, 3{Key:3, value:30}];4 5 varReformattedarray = Kvarray.map (function(obj) {6    varRobJ = {};7Robj[obj.key] =Obj.value;8    returnRobJ;9 });Ten  One //The reformattedarray array is: [{1:10}, {2:20}, {}], A  - //The Kvarray array has not been modified: - //[{key:1, value:10}, the //{key:2, value:20}, - //{key:3, value:30}]

Mapping a numeric array with a function that has only one parameter

The following code shows how the map works when a function needs a parameter. This parameter iterates through the elements in the original array.

1 var numbers = [1, 4, 9]; 2 var doubles = Numbers.map (function(num) {3   return num * 2; 4 }); 5 6 // the value of the doubles array is: [2, 8,] 7 // numbers array not modified: [1, 4, 9]

一般的 mapMethod

The following example shows how to String use the map method on one to get an array of ASCII code that corresponds to each character in a string:

1 var map = Array.prototype.map2varfunction3   return x.charcodeat (04})5//  A has a value of [72, 101, 108, 108, 111, +, 111, 108

querySelectorAll 应用

The following code shows how to traverse thequerySelectorAll 得到的动态对象集合。在这里,我们获得了文档里所有选中的选项,并将其打印:

1 var elems = Document.queryselectorall (' Select option:checked '); 2 var function (obj) {3   return Obj.value; 4 });

Invert string
1 var str = ' 12345 '; 2 function (x) {3   return  x; 4 }). Reverse (). Join ('56//  output: ' 54321 '7  //  bonus:use ' = = = ' To test if original string is a palindrome

Examples of Use tips

Normally, map a function in a method callback only needs to accept one parameter, which is the array element itself that is being traversed. But this does not mean that map only callback one parameter is passed. This thought inertia may make us make a mistake that is easy to make.

1 //what does the following statement return:2["1", "2", "3"].map (parseint);3 //you may feel that [1, 2, 3]4 //but the actual result is [1, Nan, Nan]5 6 //usually when you use parseint, you only need to pass one parameter.7 //but in fact, parseint can have two parameters. The second argument is the binary number.8 //can be verified by the statement "alert (parseint.length) ===2".9 //when the map method calls the callback function, it passes three arguments: The element that is currently being traversed,Ten //the element index, the original array itself. One //The third parameter, parseint, is ignored, but the second parameter does not, that is, A //parseint The index value passed in as a binary number to use. This returns Nan. -  - functionReturnInt (Element) { the   returnparseint (element, 10); - } -  -[' 1 ', ' 2 ', ' 3 '].map (ReturnInt);//[1, 2, 3] + //a predictable result -  + //You can also use the simple arrow function, which results in the same A[' 1 ', ' 2 ', ' 3 '].map (str =parseint (str)); at  - //a much simpler way: -[' 1 ', ' 2 ', ' 3 '].map (number);//[1, 2, 3] - //Unlike ' parseint ', the following results return floating-point numbers or indices: -[' 1.1 ', ' 2.2e2 ', ' 3e300 '].map (number);//[1.1, 3e+300]

compatibility with legacy environments (Polyfill)Edit

mapIs the newly added method in the recent ECMA-262 standard, so some older browsers might not have implemented the method. In browsers that do not have native support map methods, you can use the following Javascript code to 实现它。 use the algorithm exactly as ECMA-262, 5th Edition stipulates. Assumptions Object , TypeError and Array have their original values. and callback.call the original value isFunction.prototype.call

1 //implement ECMA-262, Edition 5, 15.4.4.192 //reference: http://es5.github.com/#x15.4.4.193 if(!Array.prototype.map) {4Array.prototype.map =function(callback, Thisarg) {5 6     varT, A, K;7 8     if( This==NULL) {9       Throw NewTypeError ("This is a null or not defined");Ten     } One  A     //1. Assign o to the array that calls the map method. -     varO = Object ( This); -  the     //2. Assign Len to the length of the array O. -     varLen = o.length >>> 0; -  -     //3. If callback is not a function, the TypeError exception is thrown. +     if(Object.prototype.toString.call (callback)! = "[Object Function]") { -       Throw NewTypeError (callback + "is not a function"); +     } A  at     //4. If the parameter thisarg has a value, the T is assigned to THISARG; otherwise t is undefined. -     if(thisarg) { -T =Thisarg; -     } -  -     //5. Create a new array A, length is the original array o length len inA =NewArray (len); -  to     //6. Assign a value of K to 0 +K = 0; -  the     //7. When K < Len executes the loop. *      while(K <Len) { $ Panax Notoginseng       varKvalue, Mappedvalue; -  the       //Traverse O,k as the original array index +       if(kinchO) { A  the         //Kvalue the value corresponding to the index K. +Kvalue =o[K]; -  $         //the execution callback,this points to T, with three parameters. Kvalue: value, K: Index, O: the original array. $Mappedvalue =Callback.call (T, Kvalue, K, O); -  -         //The return value is added to the new array A. thea[K] =Mappedvalue; -       }Wuyi       //k self-increment 1 thek++; -     } Wu  -     //8. Return the new array a About     returnA; $   };  -}

Also see: http://www.cnblogs.com/rocky-fang/p/5756733.html//Introduction to some of JS's common functions

Original address: Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map//JS Standard Library

The map method of JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.