JS中map 与 forEach 的对比

来源:互联网 发布:tomcat gzip js css 编辑:程序博客网 时间:2024/06/07 17:00

map 与 forEach 的用法:
var arr = [1,2,3,4,5]

1.相同点:用法一样

arr.map(function(v,i){    console.log(v,i)})arr.forEach(function(v,i){    console.log(i,v)})

2.不同点:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map

a. map 在对数组遍历过程,加工数组元素,最后返回一个新的数组,原数组不变;

var new_arr = arr.map(function(v,i){return i*2})console.log('旧数组',arr)console.log('新数组',new_arr)

官方示例:

var map = Array.prototype.map;var a = map.call('Hello World', function(x) {   return x.charCodeAt(0); });a // [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

个人思维拓展:
(1).可以应用对 json 数组数据进行修饰(小数点截取等)

(2).可以对新数组进行翻转

var map = Array.prototype.map;var a = map.call('Hello World', function(x) {   return x.charCodeAt(0); }).reverse()

(3).用于数组内容格式化:

['1', '2', '3'].map( str => parseInt(str) );['1', '2', '3'].map(Number); // [1, 2, 3]['1', '2', '3'].map(returnInt); // [1, 2, 3]function returnInt(ele){    return parseInt(ele,10)}

b. forEach 简单的遍历,不返回任何东西;

var testbb = arr.forEach(function(v,i){console.log(i,v)    return i*2})testbb // undefined
原创粉丝点击