一道JS笔试题,刷新了我对map方法函数的认知,你做对了吗?

 背景

昨天在看一道笔试题的时候本以为很简单,但是结果不是我想象的那样,直接上笔试题。

 
 
 
 
  1. const array = new Array(5).map((item) => {
  2.   return item = {
  3.     name: '1'
  4.   }
  5. });
  6. console.log(array);
  7. // 请写出输出结果

「我想象的答案」:[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];

「实际的答案」:[empty × 5]

为什么会这样了?

猜想1

我第一个想到的是new Array(5)生成的数组是[undefined, undefined, undefined, undefined, undefined]。

 
 
 
 
  1. const array = [undefined, undefined, undefined, undefined, undefined];
  2. const newArr = array.map((item) => {
  3.   return item = {
  4.      name: '1'
  5.    }  
  6. });
  7. console.log(newArr);
  8. // 结果是[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];

「猜想1错误」

猜想2

new Array(5)生成的数组在每一项都没有值,意思就是生成了[,,,,,]一个这样的数组。

 
 
 
 
  1. const array = [,,,,,];
  2. const newArr = array.map((item) => {
  3.   return item = {
  4.      name: '1'
  5.    }  
  6. });
  7. console.log(newArr);
  8. // 结果是[empty × 5];

「猜想2正确」

为什么

  • 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 (including undefined). It is not called for missing elements of the array; that is:
  • indexes that have never been set;
  • which have been deleted; or
  • which have never been assigned a value.

map依次为数组中的每个元素调用一次提供的callback函数,然后根据结果构造一个新的数组。-----仅对已分配值(包括)的数组索引进行调用----。map函数的回调函数只会被赋过值的项调用。new Array(1) 和 [undefined]不一样。new Array(1)没有为数组中的项赋过值,而[undefined]为数组中的项赋了一个undefined值。

总结

new Array(5)产生的数组是一个没有为数组中的项赋过值的数组。map仅对已分配值(包括)的数组索引进行callback调用。

对map方法的深入思考

 
 
 
 
  1. const array = new Array(5)

可以理解成

 
 
 
 
  1. const array = []
  2. array.length = 5

也可以理解

 
 
 
 
  1. const array = [,,,,,]

但是这里让我产生一个疑问:

以前我学习 手写map方法的时候

你百度一下,会发现也基本上很多人都是这样手写的:

 
 
 
 
  1. Array.prototype.MyMap = function(fn, context){
  2.   var arr = Array.prototype.slice.call(this);//由于是ES5所以就不用...展开符了
  3.   var mappedArr = [];
  4.   for (var i = 0; i < arr.length; i++ ){
  5.     mappedArr.push(fn.call(context, arr[i], i, this));
  6.   }
  7.   return mappedArr;
  8. }

这样似乎没啥问题,但是 这个map的手写源码 根本解释不通上面返回[empty × 5]的现象。

我们可以看一下返回结果:

如图所示,我的天,这不是坑人吗!

那真正的map方法应该死怎样实现的呢?

我猜想它应该会去遍历每一项,并且判断当前项是否为empty,是的话就不执行里面的操作,「里面指的是for循环里面的代码」

好的,问题来了,怎么判断当前项是empty?确实难倒我了,为此,我们去看下map的真正源码吧!

依照 ecma262 草案,实现的map的规范如下:

下面根据草案的规定一步步来模拟实现map函数:

 
 
 
 
  1. Array.prototype.map = function(callbackFn, thisArg) {
  2.   // 处理数组类型异常
  3.   if (this === null || this === undefined) {
  4.     throw new TypeError("Cannot read property 'map' of null or undefined");
  5.   }
  6.   // 处理回调类型异常
  7.   if (Object.prototype.toString.call(callbackfn) != "[object Function]") {
  8.     throw new TypeError(callbackfn + ' is not a function')
  9.   }
  10.   // 草案中提到要先转换为对象
  11.   let O = Object(this);
  12.   let T = thisArg;
  13.   
  14.   let len = O.length >>> 0;
  15.   let A = new Array(len);
  16.   for(let k = 0; k < len; k++) {
  17.     // 还记得原型链那一节提到的 in 吗?in 表示在原型链查找
  18.     // 如果用 hasOwnProperty 是有问题的,它只能找私有属性
  19.     if (k in O) {
  20.       let kValue = O[k];
  21.       // 依次传入this, 当前项,当前索引,整个数组
  22.       let mappedValue = callbackfn.call(T, KValue, k, O);
  23.       A[k] = mappedValue;
  24.     }
  25.   }
  26.   return A;
  27. ``}

这里解释一下, length >>> 0, 字面意思是指"右移 0 位",但实际上是把前面的空位用0填充,这里的作用是保证len为数字且为整数。

举几个特例:

 
 
 
 
  1. null >>> 0  //0
  2. undefined >>> 0  //0
  3. void(0) >>> 0  //0
  4. function a (){};  a >>> 0  //0
  5. [] >>> 0  //0
  6. var a = {}; a >>> 0  //0
  7. 123123 >>> 0  //123123
  8. 45.2 >>> 0  //45
  9. 0 >>> 0  //0
  10. -0 >>> 0  //0
  11. -1 >>> 0  //4294967295
  12. -1212 >>> 0  //4294966084

总体实现起来并没那么难,需要注意的就是使用 in 来进行原型链查找。同时,如果没有找到就不处理,能有效处理稀疏数组的情况。

最后给大家奉上V8源码,参照源码检查一下,其实还是实现得很完整了。

 
 
 
 
  1. function ArrayMap(f, receiver) {
  2.   CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");
  3.   // Pull out the length so that modifications to the length in the
  4.   // loop will not affect the looping and side effects are visible.
  5.   var array = TO_OBJECT(this);
  6.   var length = TO_LENGTH(array.length);
  7.   if (!IS_CALLABLE(f)) throw %make_type_error(kCalledNonCallable, f);
  8.   var result = ArraySpeciesCreate(array, length);
  9.   for (var i = 0; i < length; i++) {
  10.     if (i in array) {
  11.       var element = array[i];
  12.       %CreateDataProperty(result, i, %_Call(f, receiver, element, i, array));
  13.     }
  14.   }
  15.   return result;
  16. }

我们可以看到。「其实就是用key in array 的操作判断当前是否为empty。」 可不是嘛,key都没有,当然是empty了。

另外我们不能用var arrMap的方式去初始化一个即将返回的新数组,看源码。发现是要通过new Array(len)的方式去初始化

所以我们这样实现map方法 可以这样去优化

 
 
 
 
  1. Array.prototype.MyMap = function(fn, context){
  2.     var arr = Array.prototype.slice.call(this);;
  3.     var mapArr = new Array(this.length);
  4.     
  5.     for (var i = 0; i < arr.length; i++ ){
  6.      if (i in arr) {
  7.         mapArr.push(fn.call(context, arr[i], i, this));
  8.      }
  9.     }
  10.     return mapArr;
  11.   }

嘿嘿!感觉下一次面试遇到这个问题,我可以吹牛了!

为什么 key in Array 可以判断 当前项是否为 empty呢?

这个就要涉及到 一个对象的「常规属性」和 「排序属性」

由于以前我已经写过文章来解释过 这两个东西,我就不再赘述了,大家可以点击这篇文章进去看看,里面利用一道面试题讲解了「常规属性」和 「排序属性」

百度前端面试题:for in 和 for of的区别详解以及为for in的输出顺序

我们可以看到文章里面这张图。是不是可以发现 2 in bar 是false的 因为 这个 为2的key 根本就不在 element上。

参考文章

【手写数组的 map 方法 ?】http://47.98.159.95/my_blog/blogs/javascript/js-array/006.html

【这道JS笔试题你做对了吗?】https://juejin.cn/post/6844904032507559944

本文标题:一道JS笔试题,刷新了我对map方法函数的认知,你做对了吗?
当前路径:http://www.hantingmc.com/qtweb/news40/424640.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联