关于arr.map()问题

最近看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。上面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

猜你喜欢

转载自www.cnblogs.com/qingfengliuyun092815/p/10717562.html
Arr
今日推荐