数组常用方法 reverse / filter / map / concat / forEach 之介绍
var arr = [32, 33, 16, 40]
1.arr.reverse()
---------- 颠倒数组中元素的顺序。
// 40,16,33,32
:注意:会改变原来的数组,而不会创建新的数组
2.arr.filter()
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
eg:arr.filter( (item,index,arr) => { return item>18 })
// 32,33,40
语法
array.filter(function(currentValue,index,arr), thisValue)
参数说明
参数 |
描述 |
function(currentValue, index,arr) |
必须。函数,数组中的每个元素都会执行这个函数
函数参数:
|
thisValue |
可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"
|
参数 |
描述 |
currentValue |
必须。当前元素的值 |
index |
可选。当前元素的索引值 |
arr |
可选。当前元素属于的数组对象 |
3.arr.map()
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
eg:arr.map((item) => {return (item+2)})
语法
array.map(function(currentValue,index,arr), thisValue)
参数说明
参数 |
描述 |
function(currentValue, index,arr) |
必须。函数,数组中的每个元素都会执行这个函数
函数参数:
|
thisValue |
可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"
|
参数 |
描述 |
currentValue |
必须。当前元素的值 |
index |
可选。当期元素的索引值 |
arr |
可选。当期元素属于的数组对象 |
4.arr.concat()
concat() 方法用于连接两个或多个数组。
该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本。
arrayObject.concat(arrayX,arrayX,......,arrayX)
返回值
返回一个新的数组。该数组是通过把所有 arrayX 参数添加到 arrayObject 中生成的。如果要进行 concat() 操作的参数是数组,那么添加的是数组中的元素,而不是数组。
eg:
5.arr.forEach()
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
eg:arrList.forEach(item => {
item.product = Arr_PRODUCT_LIST.filter(product => +product.price == item.amount/item.quantity).pop() || {};
item.statusItem = this.statusColorBox[item.status]
console.log(item);
});
语法
array.forEach(function(currentValue, index, arr), thisValue)
参数
参数 |
描述 |
function(currentValue, index, arr) |
必需。 数组中每个元素需要调用的函数。
函数参数:
|
thisValue |
可选。传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
|
参数 |
描述 |
currentValue |
必需。当前元素 |
index |
可选。当前元素的索引值。 |
arr |
可选。当前元素所属的数组对象。 |