關於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,把參數傳入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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM