var ary = [12,23,24,42,1]; var res = ary.forEach(function (item,index,input) { input[index] = item*10; }) console.log(res);//-->undefined; console.log(ary);//-->會對原來的數組產生改變;
var ary = [12,23,24,42,1]; var res = ary.map(function (item,index,input) { return item*10; }) console.log(res);//-->[120,230,240,420,10]; console.log(ary);//-->[12,23,24,42,1];
/** * forEach遍歷數組 * @param callback [function] 回調函數; * @param context [object] 上下文; */ Array.prototype.myForEach = function myForEach(callback,context){ context = context || window; if('forEach' in Array.prototye) { this.forEach(callback,context); return; } //IE6-8下本身編寫回調函數執行的邏輯 for(var i = 0,len = this.length; i < len;i++) { callback && callback.call(context,this[i],i,this); } }
/** * map遍歷數組 * @param callback [function] 回調函數; * @param context [object] 上下文; */ Array.prototype.myMap = function myMap(callback,context){ context = context || window; if('map' in Array.prototye) { return this.map(callback,context); } //IE6-8下本身編寫回調函數執行的邏輯 var newAry = []; for(var i = 0,len = this.length; i < len;i++) { if(typeof callback === 'function') { var val = callback.call(context,this[i],i,this); newAry[newAry.length] = val; } } return newAry; }