yym-yumeng123 / Interview

学习中的一些问题
3 stars 1 forks source link

实现一个map()函数,模拟原生的map函数, map(list,iteratee) #35

Open yym-yumeng123 opened 7 years ago

yym-yumeng123 commented 7 years ago

通过对list里的每个元素调用转换函数(iteratee迭代器)生成一个与之相对应的数组.iteratee传递三个参数:value,然后是迭代index.

ex:
map([1,2,3],function(num){return num *3})  ==>[3,6,9]
解答:
function map(arr,fn){
  var newArr = []
  for(var i = 0;i < arr.length; i++){
    newArr.push(fn(arr[i]))
  }
  return newArr
}
var result = map([1,2,3],function(num){return num*3})
console.log(result)  //[3, 6, 9]
yym-yumeng123 commented 7 years ago
function map(list,iteratee){
  var result = []
  for(var index = 0; index < list.length; index++){
    result[index] = iteratee(list[index],index)
  }
  return result
}
var result = map([1,2,3,4],function(num){return num *4})
console.log(result)