map 映射
函数定义
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
一个简单的map映射示例
'use strict'
var list = [1, 2, 3, 4, 5];
var newList = list.map(value => value * 2);
console.log(newList);
// [ 2, 4, 6, 8, 10 ]
使用map映射对象数据,给每个元素添加新的属性
'use strict'
var list = [
{
name: "Tom",
age: 10
},
{
name: "Jack",
age: 20
}
];
var newList = list.map((item, index)=>{
return {
index: index,
name: item.name,
age: item.age + 1,
active: false
}
});
console.log(newList);
/**
[
{
index: 0,
name: 'Tom',
age: 11,
active: false
},
{
index: 1,
name: 'Jack',
age: 21,
active: false
}
]
*/
forEach 迭代
函数定义
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
使用 forEach 给列表添加属性
'use strict'
var list = [
{
name: "Tom",
age: 10
},
{
name: "Jack",
age: 20
}
];
list.forEach((item, index)=>{
item.age = item.age + 1;
item.active = false;
item.index = index;
});
console.log(list);
/**
[
{
name: 'Tom',
age: 11,
active: false,
index: 0
},
{
name: 'Jack',
age: 21,
active: false,
index: 1
}
]
*/
区别
map 和 forEach 都是迭代列表元素,参数都相同
map有返回值,forEach无返回值