码迷,mamicode.com
首页 > 其他好文 > 详细

关于arr.map()问题

时间:2019-04-16 16:34:50      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:javascrip   []   new   ret   接受   contex   asc   ror   三次   

最近看map实现原理,

Array.prototype._map = function(fn, context) {
	console.log(fn, context)
        var temp = [];
	if(typeof fn == ‘function‘) {
	      var k = 0;
	      var len = this.length;
	      for(; k < len; k++) {
		    temp.push(fn.call(context, this[k], k, this))
	     }
	} else {
	     console.error(‘TypeError: ‘+ fn +‘ is not a function.‘);
        }

	return temp;
}

  map接受两个参数,一个fn函数,一个是obj目标对象,这里context为undefined,通过fn.call(undefined,arg1,arg2)把改变this指向为window,把参数传入fn。上面this[k], k, this,this为数组,this[k]为数组的值,k为下标index。可以通过

[1,2,3].map(function(item, index, obj){console.log(item, index,obj)})

  来查看参数

  这里有个经典面试题,

var newArr = [‘1‘, ‘2‘, ‘3‘]._map(parseInt)
console.log(newArr) // [1, NaN, NaN]

  下面解释下为什么,这里由于parseInt是可以接受第二个参数的,这个参数为0的时候为十进制且2到36之间,我们按照数组循环来查看一下parseInt的参数,第一次三个参数‘1’,0,[‘1‘,‘2‘,‘3‘],显然这里结果为1,第二层‘2’,1,[‘1‘,‘2‘,‘3‘],这里为NaN,第三次‘3’,2,[‘1‘,‘2‘,‘3‘],运行为parseInt(‘3’,2),显然为NaN

关于arr.map()问题

标签:javascrip   []   new   ret   接受   contex   asc   ror   三次   

原文地址:https://www.cnblogs.com/qingfengliuyun092815/p/10717562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!