In-depth understanding Array.prototype.map ()

Overview:

  Returns the value of the new array of map () method returns an array of a specified original method call after each element, it does not change the original array.

  grammar:

  let newArr = oldArr.map(callback[, thisArg])

parameter:

  callback

    After the original array element calls the method returns a new array. It receives three parameters, namely currentValue, index, array.

    currentValue

      The first argument of the callback, the array elements of the current to be delivered.

    index (optional)

      The second callback parameter, the index of the current element in the array is transferred.

    Array (Optional)

      The third parameter callback, call array () method of the map, i.e., the original array.

  thisArg (optional)

    When you do this as an object callback function.

 

description

    map () method will give each element of the original array are sequentially called once callback function. callback return value after execution of each combined to form a new array. callback function will be called on the index has value, that had never been assigned a value or use delete to delete the index will not be called.

    callback function will be automatically passed three parameters: the array element, the array element index, the original array itself.

    If there is thisArg parameter value, callback function each time you call, this will point to the object on the thisArg parameters. If omitted thisArg parameters, or to assign null or undefined, this refers to the global object.

    Using the map () method when processing array, the array elements is in a range before the callback function is called for the first time is determined. In the process of map () method executed: the original array of newly added elements will not be accessible to the callback; if existing elements are changed or deleted, they are passed to the callback value is a map () method to iterate they value the moment; and deleted elements will not be accessible.

Examples

1. The square root of each element of the array

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

  

Code Package:

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]

Processing method requires only incoming correspondence, you can make a batch for all array elements.

Of course, this method may be the second package :

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]

 

2.将数组中的单词转换成复数形式。

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));  //每个元素都按顺序调用一次fuzzyPlural函数

//返回["feet","geese","meese","kangareese"];

 

3.使用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;
});
// reformattedArry数组为: [{1: 10}, {2: 20}, {3: 30}]

// kvArray 数组未被修改: 
// [{key: 1, value: 10}, 
//  {key: 2, value: 20}, 
//  {key: 3, value: 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]]

 

 

 

4.反转字符串

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('');

console.log(reverseString('foobar')) // 'raboof'

 

 

5.将字符串转为ASIIC码组成的数组

 

var map = Array.prototype.map;
var a = map.call("hello world",function(x){ return x.charCodeAt(0);})

//a的值为[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

 

 

代码封装:

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

 

6.Dom操作

遍历用 querySelectorAll 得到的动态对象集合。在这里,我们获得了文档里所有选中的选项,并将其打印

 

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

 

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

 相比看完上面的解说觉得自己已经深入理解了吧,那么在看下面一个例子

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

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

这是为什么呢?

   通常情况下,map 方法中的 callback 函数只需要接受一个参数,就是正在被遍历的数组元素本身。但这并不意味着 map 只给 callback 传了一个参数。这个思维惯性可能会让我们犯一个很容易犯的错误。

 

// 下面的语句返回什么呢:
["1", "2", "3"].map(parseInt);
// 你可能觉的会是[1, 2, 3]
// 但实际的结果是 [1, NaN, NaN]

// 通常使用parseInt时,只需要传递一个参数.
// 但实际上,parseInt可以有两个参数.第二个参数是进制数.
// 可以通过语句"alert(parseInt.length)===2"来验证.
// map方法在调用callback函数时,会给它传递三个参数:当前正在遍历的元素, 
// 元素索引, 原数组本身.
// 第三个参数parseInt会忽视, 但第二个参数不会,也就是说,
// parseInt把传过来的索引值当成进制数来使用.从而返回了NaN.

function returnInt(element) {
  return parseInt(element, 10);
}

['1', '2', '3'].map(returnInt); // [1, 2, 3]
// 意料之中的结果

// 也可以使用简单的箭头函数,结果同上
['1', '2', '3'].map( str => parseInt(str) );

// 一个更简单的方式:
['1', '2', '3'].map(Number); // [1, 2, 3]
// 与`parseInt` 不同,下面的结果会返回浮点数或指数:
['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]

 

8.封装Array.prototype.map()方法

下面是实现map方法的函数封装。 暂时只是实现了基础功能,具体还有很多优化可以做。

   function myMap(data, fn) {
        var arg = [];
        for (var i = 0; i < data.length; i++) {
            (function (ele, fn) {
            //每一个元素处理后放入新数组
                arg.push(fn(ele));
            })(data[i], fn);
        }
        return arg;
    }
    var data = [10, 20, 30, 40];
    var roots= myMap(data, function (ele) {
        return ele / 10;
    });
    console.log(roots);//[1,2,3,4]

 

 

参考资料:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 

 

Guess you like

Origin www.cnblogs.com/jing-tian/p/11119999.html