数组的map()和forEach()方法的区别
1、map()方法返回一个新数组:方法里必须return item项
2、map()方法不对空数组进行检测
3、map()方法不会改变原始数组:原始数组的数据类型为基本类型的话,保持不变;数据类型如果为引用类型的话,引用地址不变,
但是具体的内容是可以改变的。如果需要遍历一个数组,只是想修改这个数组的某些属性,直接赋值就好,不用return 后重新赋值新数组
var arr1 = [
{ username: "牛", usercode: "123" },
{ username: "张", usercode: "456" },
];
var arr2 = arr1.map((item) => {
item.usercode = item.usercode + "NF";
return item;
});
console.log(arr1);
console.log(arr2);
// (2) [{…}, {…}]
// 0: {username: '牛', usercode: '123NF'}
// 1: {username: '张', usercode: '456NF'}
// length: 2
// [[Prototype]]: Array(0)
// VM79:10
// (2) [{…}, {…}]
// 0: {username: '牛', usercode: '123NF'}
// 1: {username: '张', usercode: '456NF'}
// length: 2
// [[Prototype]]: Array(0)
// 1、map()方法返回一个新数组:方法里必须return item项
var arr3 = [1, 2, 3, 4, 5];
var arr4 = arr3.map((item) => {
return item * 2;
});
console.log(arr3);
console.log(arr4);
// (5) [1, 2, 3, 4, 5]
// (5) [2, 4, 6, 8, 10]
// map()方法不对空数组进行检测
var arr5 = [];
var arr6 = arr5.map((item) => {
return item + 1;
});
console.log(arr5);
console.log(arr6);
// []
// []
1、forEach在对item进行修改的时候,如果item是基本类型,item 对应的 的内存地址实际并没有变化,
如果 item 是 引用类型的值,item 对应多的内存地址也没有变化,但是对应的值,已经重写了
2、如果要使用数组的forEach()方法对其改值时,需要直接通过arr[i]这种方式来更改。
var arr7 = [1, 2, 3, 4, 5];
arr7.forEach((item) => {
item = item * 2;
});
console.log(arr7);
// [1, 2, 3, 4, 5]
var arr8 = [
{ username: "牛", usercode: "123" },
{ username: "张", usercode: "456" },
];
arr8.forEach((item) => {
item.usercode = item.usercode + "NF";
});
console.log(arr8);
// (2) [{…}, {…}]
// 0: {username: '牛', usercode: '123NF'}
// 1: {username: '张', usercode: '456NF'}
// length: 2
// [[Prototype]]: Array(0)
var arr9 = [1, 2, 3, 4, 5];
arr9.forEach((item, index, arr9) => {
arr9[index] = item * 2;
});
console.log(arr9);
// (5) [2, 4, 6, 8, 10]