map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组,forEach为数组中的每个元素执行一次回调函数。
map()方法
若这个回调函数有返回值,map()方法会产生一个新数组,这个新数组由原数组元素对应的回调函数的返回值构成。若没有返回值,则新数组的所有元素为undefined。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
array.map(function(currentValue,index,arr), thisValue)
- currentValue 必需。当前元素
- index 可选。当前元素的索引值。
- arr 可选。当前元素所属的数组对象。
- thisValue可选。传递给函数的值一般用 “this” 值。如果这个参数为空, this指向window
demo01 不修改原数组的情况下,返回一个新的对象数组:
var test = [{a: 1, b: 2}];
var x = test.map(function (currentValue, index, arr) {
return {
a : currentValue.a + 10000,
b : currentValue.b + 10000
};
});
console.log(test[0].a);//1
console.log(x[0].a);//10001
demo02 不修改原数组的情况下,返回一个新的数组:
var test = [1,2,3];
var x = test.map(function (currentValue, index, arr) {
return currentValue + 1
});
console.log(test);//[1,2,3]
console.log(x);//[2,3,4]
demo03 利用map返回一个数组,数组成员是对象的方法:
export default class Store {
obj ={};
@observable todos = [{
title: 111,
done: 1
},{
title: 222,
done: 2
}];
@action changeTodoTitle(index, title) {
this.todos[index].title = title
};
@computed get finishedTodos(){
return (this.todos.map((value, index) =>(
{
title : value.title + 1,
done : value.done + 1
}
)
))
}
}
箭头函数如果要返回一个对象则需要先使用()然后使用表示对象的{}(引入在箭头函数后面的{}首先被理解为代码块)
forEach()方法
仅仅为每个数组元素执行回调函数。注意: forEach() 对于空数组是不会执行回调函数的。
array.forEach(function(currentValue, index, arr), thisValue)
- currentValue 必需。当前元素
- index 可选。当前元素的索引值。
- arr 可选。当前元素所属的数组对象。
- thisValue可选。传递给函数的值一般用 “this” 值。如果这个参数为空, this指向window
demo01 : 没有返回值,对数组本身不能修改,但是可以修改数组中对象的属性
var test = [{a: 1, b: 2}];
test.forEach(function (currentValue, index, arr) {
currentValue.a = 10000;
});
console.log(test[0].a);//10000
var test2 = [1, 2, 3];
test2.forEach(function (currentValue, index, arr) {
currentValue = 10000;
});
console.log(test2[0]);//1
demo02 : 第二个参数默认改变了this的指向
var a = 100;
var b = {
a : 10000
};
var test = [{a:1,b:2}];
test.forEach(function(currentValue, index, arr){
console.log(this.a)// 100
});
test.forEach(function(currentValue, index, arr){
console.log(this.a)// 100
}, window);
test.forEach(function(currentValue, index, arr){
console.log(this.a)// undefined
}, test);
test.forEach(function(currentValue, index, arr){
console.log(this.a)// 10000
}, b);