导读
- array.forEach()
- map()
- array.filter()
- array.every()
- array.find()
- array.findIndex()
- array.filter()
array.forEach()
- array:数组
- for:为了……
- Each:每一个
定义 - 官网:按顺序为数组中的每个元素调用一次函数。
- 理解:指定函数遍历数组。意思就是为数组中的每一个元素执行一次函数。
语法
array.forEach(function(currentValue.index.arr),thisValue)
- function:第一个参数是一个函数
- 当执行forEach()方法的时候,每个数组元素都会调用一次函数参数。
- 在调用函数的时候,可以传入以下三个参数:
- item:表示数组中的一个元素。(必须)
- index:表示数组中的索引(可选)
- Array:表示当前数组(可选)
- thisValue:第二个人参数是设置this指向。(可选)
返回值
- undefined
示例
每个加3
var arr = [1, 2, 3];
arr.forEach(function (item, index) {
arr[index] = item + 3;
});
console.log(arr); //返回值456
求平均值
let sum = 0;
const arr = [1, 2, 3];
arr.forEach(function (item) {
sum += item;
});
console.log(sum); //返回值6
map()
定义
- 数组中的元素为原始数组元素调用函数处理后的值
- 按照原始数组元素顺序依次处理元素
语法
array.map(function(currentValue,index,arr),thisValue)
- 参数:
currentValue 必须。当前元素的值
index 可选。当前元素的索引值
arr 可选。当前元素属于的数组对象
返回值
一个新数组
示例
var arr = [1,2,3];
let arrNew = []
arrNew = arr.map(function(item,index){
return item + 3
});
console.log(arrNew) //[ 4, 5, 6 ]
array.filter()
定义
- 创建数组,填充了所有通过测试的数组元素(作为函数提供)
语法 - array.filter(function(currentValue, index, arr), thisValue)
返回值 - 包含所有通过测试的数组元素的数组。如果没有元素通过测试,则返回一个空数组。
示例
var arr = [10, 20, 30, 40, 50];
var arr1 = [];
arr1 = arr.filter(function (item) {
return item > 30;
});
console.log(arr1); //[40,50]
array.every()
定义
- 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)
语法
array.every(function(currentValue,index,arr), thisValue)
- 参数:
- currentValue 必须。当前元素的值
- index 可选。当前元素的值
- arr 可选。当前元素属于数组的对象
返回值
- 布尔值。如果所有元素都通过检测返回 true,否则返回 false。
示例
var arr = [1,2,3]
var arr1 = arr.every(function)(item,index,arr{
return item > 1
})
//返回值flase
array.find()
定义
-
find()
方法返回数组中第一个通过测试元素的值(作为函数提供)
语法
array.find(function(currentValue, index, arr), thisValue)
- 参数:
- currentValue 必选。当前元素的值
- index 可选。当前元素的数组索引
- arr 可选。当前元素所属的数组对象
返回值
- 数组中元素通过测试,则返回数组元素值,否则返回undefined。
示例
var arr = [1,2,3]
var arr1 = arr.find(function(item,index,arr){
return item === 1
})
//返回值是1
array.findIndex()
定义
-
findIndex()
返回数组中通过测试的第一个元素的索引(作为函数提供)
语法
array.findIndex(function(currentValue, index, arr), thisValue)
- 参数:
- currentValue 必需。当前元素的值。
- index 可选。当前元素的数组索引。
- arr 可选。当前元素所属的数组对象。
返回值
- 返回符合测试条件的第一个数组元素索引,如果没有符合条件的则返回-1
示例
var arr = [20, 30, 40, 50, 60, 70];
var arr1 = arr.findIndex(function (item) {
return item == 50;
});
console.log(arr1);
// 返回值:3
如何没有检测到则返回-1
array.filter()
定义
-
filter
方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
语法
array.filter(function(currentValue,index,arr), thisValue)
- 参数:
- currentValue 必须。当前元素的值
- index 可选。当前元素的索引值
- arr 可选。当前元素属于的数组对象
返回值
- 返回数组,包含符合条件的所有元素。如果没有符合条件的元素则返回空数组。
示例
var arr = [1,2,3]
var arr1 = arr.filter(function(item,index,arr){
retuen.item > 1
//返回值:[2,3]
})