map函数的使用技巧

来源:互联网 发布:php手机短信验证源码 编辑:程序博客网 时间:2024/06/07 16:57

js的Array数组对象中有很多有用的方法,js的map函数在某些方面非常的方便强大。

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

let numbers = [1, 5, 10, 15];let roots = numbers.map((x) => {    return x * 2;});let roots = numbers.map( x =>  x * 2);// roots is now [2, 10, 20, 30]// numbers is still [1, 5, 10, 15]let numbers = [1, 4, 9];// let roots = numbers.map(Math.sqrt);let roots = numbers.map(function(x){    return Math.sqrt(x);});// roots is now [1, 2, 3]// numbers is still [1, 4, 9]

map函数的使用例子

求数组中每个元素的平方根

var numbers = [1, 4, 9];var roots = numbers.map(Math.sqrt);/* roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9] */

querySelectorAll 应用

下面代码展示了如何去遍历用 querySelectorAll 得到的动态对象集合。在这里,我们获得了文档里所有选中的选项,并将其打印:

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

反转字符串

var str = '12345';Array.prototype.map.call(str, function(x) {  return x;}).reverse().join(''); // Output: '54321'// Bonus: use '===' to test if original string was a palindrome

兼容旧环境

// 实现 ECMA-262, Edition 5, 15.4.4.19// 参考: http://es5.github.com/#x15.4.4.19if (!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. 将O赋值为调用map方法的数组.    var O = Object(this);    // 2.将len赋值为数组O的长度.    var len = O.length >>> 0;    // 3.如果callback不是函数,则抛出TypeError异常.    if (Object.prototype.toString.call(callback) != "[object Function]") {      throw new TypeError(callback + " is not a function");    }    // 4. 如果参数thisArg有值,则将T赋值为thisArg;否则T为undefined.    if (thisArg) {      T = thisArg;    }    // 5. 创建新数组A,长度为原数组O长度len    A = new Array(len);    // 6. 将k赋值为0    k = 0;    // 7. 当 k < len 时,执行循环.    while(k < len) {      var kValue, mappedValue;      //遍历O,k为原数组索引      if (k in O) {        //kValue为索引k对应的值.        kValue = O[ k ];        // 执行callback,this指向T,参数有三个.分别是kValue:值,k:索引,O:原数组.        mappedValue = callback.call(T, kValue, k, O);        // 返回值添加到新数组A中.        A[ k ] = mappedValue;      }      // k自增1      k++;    }    // 8. 返回新数组A    return A;  };      }