1. forEach
语法: 数组.forEach(function(item, index, origin){})
参数:
- 数组实际每一项的值
- 数组每一项对应的下标
- 原数组
作用: 遍历数组
返回值: 返回值是 undefined 写了 return 返回值也是 undefined
var arr = [1,2,3,4,5]
var num = arr.forEach(function(item,index,origin){
return item})
console.log(num) //---> 原数组
2. map
语法: 数组.map(function (item, index, origin) {})
参数:
- 数组每一项实际的值
- 数组每一项实际的值对应的下标
- 原数组
作用: 映射数组
返回值: 返回一个和原数组长度一样的数组, 返回的数组的每一个值, 取决参数的return怎么写
var arr = [1,2,3,4,5]
var num = arr.map(function(item,index,origin){
return item*2})
console.log(num) //---> [2,4,6,8,10]
3. filter
语法: 数组.filter(function (item, index, origin) {})
参数:
- 数组每一项实际的值
- 数组每一项实际的值对应的下标
- 原数组
作用: 过滤数组
返回值: 过滤数组后的新数组, 过滤条件取决于 参数的 return 怎么写
var arr = [1,2,3,4,5]
var num = arr.filter(function(item,index,origin){
return item > 2})
console.log(num) //---> [3,4,5]
4. find
语法: 数组.find(function (item, index, origin) {})
参数:
- 数组每一项实际的值
- 数组每一项实际的值对应的下标
- 原数组
作用: 查找数据
返回值: 在数组内找到的第一个数据(不是数组)
var arr = [1,2,3,4,5]
var num = arr.find(function(item,index,origin){
return item > 3})
console.log(num) //---> 4
5. findIndex
语法: 数组.findIndex(function (item, index, origin) {})
参数:
- 数组每一项实际的值
- 数组每一项实际的值对应的下标
- 原数组
作用: 查找数据 第一次出现的 下标
返回值: 在数组内找到的第一个数据出现的下标
var arr = [1,2,3,4,5]
var num = arr.findIndex(function(item,index,origin){
return item > 3})
console.log(num) //---> 3
6. every
语法: 数组.every(function(item, index, origin){})
参数:
- 数组第一项实际的值
- 数组第一项实际的值对应的下标
- 原数组
作用: 判断数组内数据是否全都满足条件
返回值: 一个布尔值
true —> 数组内数据全都符合条件
false —> 数组内起码有一个数据 不符合条件
var arr = [1,2,3,4,5]
var num = arr.every(function(item,index,origin){
return item > 0})
console.log(num) //---> true
7. some
语法: 数组.some(function (item, index, origin) {})
参数:
- 数组每一项实际的值
- 数组每一项实际的值对应的下标
- 原数组
作用: 判断数组内数据是否 有一项 满足条件的
返回值: 一个布尔值
true: 表示数组内至少有一项满足条件
false: 数组内数据全都不满足条件
var arr = [1,2,3,4,5]
var num = arr.some(function(item,index,origin){
return item > 5})
console.log(num) //---> false
8. reduce
语法: 数组.reduce(function (prve, item, index, origin) {}, init)
reduce方法的参数:
- 如果传递第二个参数 init, 执行次数和数组长度相同
- 如果不传递第二个参数 init, 默认第一值为数组第一项的值, 并且执行次数在数组长度上 减1
参数1的函数中4个形参的含义: - 表示初始值或者数组第一项的值(具体是什么取决于是否传递 init)
- 数组每一项实际的值
- 数组每一项实际的值对应的下标
- 原数组
作用: 累加(叠加)
返回值: 循环运行结束后得到的值
不传递第二个参数
var arr = [1,2,3,4,5]
var num = arr.reduce(function(prve,item,index,origin){
return prve + item})
console.log(num) //---> 15
传递第二个参数
var arr = [1,2,3,4,5]
var num = arr.reduce(function(prve,item,index,origin){
return prve * item},2)
console.log(num) //---> 240