JavaScript数组方法学习(二):遍历数组
文章目录
前言
数组在开发中扮演着十分重要的角色,所以学会对数组的各种操作也是非常的重要。
在本文中,我将介绍部分遍历数组的方法
一、forEach()
1.介绍
定义:
forEach()方法可以调用数组的所有的元素,并将其作为回调函数的参数。
语法: array.forEach(function(currentValue, index, arr), thisValue)
参数 | 说明 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。forEach() 方法正在操作的数组。 |
thisValue | 可选。当执行回调函数 callback 时,用作 this 的值。如果不设置,或者值为null或undefined,则this指向window |
2.案例
使用forEach()遍历数组
代码如下:
let array= [1,2,3,4,5]
let res = array.forEach(function(currentValue) {
console.log(currentValue)
return true
})
console.log(res)
结果如下:
forEach()的返回值只能是undefined,我们定义变量res接收了forEach()的返回值,可以看到返回结果为undefined
使用forEach()修改数组的元素,这里将数组中的元素乘2
代码如下:
let array= [1,2,3,4,5]
array.forEach(function(currentValue,index,arr) {
arr[index] = currentValue*2
})
console.log(array)
结果如下:
使用forEach()计算总和
代码如下:
let array= [1,2,3,4,5]
let sum = 0
array.forEach(function(currentValue) {
sum += currentValue
})
console.log(sum)
结果如下:
forEach()回调函数给原数组添加元素
代码如下:
let array = [1,2,3,4,5]
let res = array.forEach(function(currentValue,index,arr) {
arr.push('@')
console.log('执行')
console.log(currentValue)
})
console.log(array)
结果如下:
可以看到,尽管在forEach()回调函数中对原数组进行了添加元素的操作,但是forEach() 遍历的范围在第一次调用 callback 前就已经被确定了
使用forEach()的回调函数删除元素
代码如下:
let array = [1,2,3,4,5]
let res = array.forEach(function(currentValue,index,arr) {
if(currentValue === 2) {
arr.shift()
}
console.log('执行')
console.log(currentValue)
})
console.log(array)
结果如下:
可以理解为,最开始要遍历的数据为[1,2,3,4,5],但是在执行删除第一个元素后的操作,且已经遍历了两个元素,剩下遍历的数据剩下[4,5],即让它们被遍历的事件提前了
二、some()
1.介绍
定义:
some() 方法测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为 false
语法: array.forEach(function(currentValue, index, arr), thisValue)
参数 | 说明 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。some() 方法正在操作的数组。 |
thisValue | 可选。当执行回调函数 callback 时,用作 this 的值。如果不设置,或者值为null或undefined,则this指向window |
2.案例
遍历非空数组和空数组
代码如下:
let array = [1,2,3,4,5]
let res = array.some(function(currentValue) {
console.log(currentValue);
})
let array1 = []
let res1 = array1.some(function() {
return true
})
console.log(res);
console.log(res1);
结果如下:
通过以上结果可以看出,some会遍历所有的元素,且没设置返回值时,其返回值为false
当一个空数组调用some()方法时,尽管return的值为true,但是接收的结果仍然为false
判断数组中是否含有小于6的数、是否含有大于6的数
代码如下:
let array = [1,2,3,4,5]
let res = array.some(function(currentValue) {
return currentValue < 6
})
let res1 = array.some(function(currentValue) {
return currentValue > 6
})
console.log('是否存在小于6的值',res);
console.log('是否存在大于6的值',res1);
结果如下:
三、every()
1.介绍
定义:
every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
语法: array.every(function(currentValue, index, arr), thisValue)
参数 | 说明 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。every() 方法正在操作的数组。 |
thisValue | 可选。当执行回调函数 callback 时,用作 this 的值。如果不设置,或者值为null或undefined,则this指向window |
2.案例
遍历空数组
代码如下:
let like = []
let res = like.every(function() {
return false
})
console.log(res);
结果如下:
我们可以从运行结果发现,当调用every()的是一个空数组时,返回的结果一定为true
判断数组里面的元素是否符合同一规则
代码如下:
let like = ['唱','跳','rap','篮球']
let res = like.every(function(cuerrentValue) {
return typeof(cuerrentValue) === 'string'
})
console.log(res);
结果如下:
从结果可以看到,数组中所有元素的类型都为string,则返回为true
代码如下:
let like = ['唱','跳','rap','篮球']
let res = like.every(function(cuerrentValue) {
return cuerrentValue === '篮球'
})
console.log(res);
结果如下:
从结果可以看到,数组中仅有一个元素符合要求,所以返回为false
四、reduce()
1.介绍
定义:
reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
语法: array.reduce(function(previousValue, currentValue, currentIndex,array), 初始值)
参数 | 说明 |
---|---|
previousValue | 可选。前一次调用 callbackfn 得到的返回值 |
currentValue | 可选。数组中正在处理的元素。 |
currentIndex | 可选。every() 方法正在操作的数组。 |
currentIndex | 可选。数组中正在处理的元素的索引 |
array | 可选。被遍历的对象 |
2.案例
数组求和(有初始值)
代码如下:
let numArr = [1,2,3,4]
let sum = numArr.reduce((previousValue,currentValue) => {
return previousValue + currentValue
},10)
console.log('结果:',sum);
结果如下
数组求和(无初始值)
代码如下:
let numArr = [1,2,3,4]
let sum = numArr.reduce((previousValue,currentValue) => {
return previousValue + currentValue
})
console.log('结果:',sum);
结果如下
前一次调用 callbackfn 得到的返回值
代码如下:
let numArr = [1,2,3,4]
let sum = numArr.reduce((previousValue,currentValue) => {
console.log(previousValue);
return previousValue + currentValue
})
console.log('结果:',sum);
结果如下:
求元素在数组中出现的个数
代码如下:
let numArr = [1,1,1,2,3,3,4,4,4,4,4]
let countNum = numArr.reduce((previousValue,currentValue) => {
if(currentValue in previousValue) {
previousValue[currentValue] ++
}else {
previousValue[currentValue] = 1
}
return previousValue
},{})
console.log('结果:',countNum);
结果如下:
这里将传入的初始值设置为对象,将回调函数前一刻的值,在对象中被定义为属性,如果该属性不存在,则将其初始值设置为1,表示已经存在这个值,数量为1;当已存在这个属性,则将其数量加1,最后返回这个对象即可。
五、fill()
1.介绍
定义:
fill() 方法将开始索引到结束索引的值填充为其它的值,不包括结束索引
语法: array.fill(value,start,end)
参数 | 说明 |
---|---|
value | 可选。用来填充数组元素的值。 |
start | 可选。起始索引,默认值为 0。 |
end | 可选。终止索引,默认值为 this.length。 |
2.案例
填充数组
代码如下:
let arr = [1,2, , , 6]
console.log(arr.fill('填充',2,3));
结果如下:
这里原数组将下标为二,和下标为三的位置设置为空白,仅填充了下标为2的地方
六、flat()
1.介绍
定义:
flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
语法: array.flat(depth)
参数 | 说明 |
---|---|
depth | 默认为1,可以设置正整数表示提取嵌套数组的结构深度,使用Infinity将展开任意深度 |
2.案例
使用flat()移除数组中的空项
代码如下:
let arr = [1,2,,,,,7]
console.log(arr.flat());
结果如下:
depth为2
代码如下:
let arr = [1,2,[3],[[4],[5]],[[[6]]]]
console.log(arr.flat(2));
结果如下:
将depth设置为2时,最多可以提取深度为2的
depth为Infinity
代码如下:
let arr = [1,2,[3],[[4],[5]],[[[6]]]]
console.log(arr.flat(Infinity));
结果如下:
可以看到,将depth设置为Infinity,可以提取所有深度
七、filter()
1.介绍
定义:
过滤器,filter() 方法创建一个新数组,其包含通过所提供函数实现的测试的所有元素。
语法: array.filter(function(currentValue, index, arr), thisValue)
参数 | 说明 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。filter() 方法正在操作的数组。 |
thisValue | 可选。当执行回调函数 callback 时,用作 this 的值。如果不设置,或者值为null或undefined,则this指向window |
2.案例
计算选中商品总价
代码如下:
/*
name:商品名称
state:选中状态
price:单价
count:数量
*/
let arr = [
{name: 'apple', state: true, price: 10, count: 5},
{name: 'banana', state: false, price: 5, count: 1},
{name: 'orange', state: true, price: 3, count: 6}
]
let totalPrice = arr.filter(function(item) {
return item.state === true
}).reduce(function(previousValue,currentValue,_,arr) {
console.log('过滤后的数组:',arr);
return previousValue += currentValue.price * currentValue.count
},0)
console.log('总价:',totalPrice);
结果如下:
在这里我做了一个综合性的案例,首先使用filter()方法,过滤出了state状态为true的商品,由于filter()返回的是一个新的数组,所以,它自然可以调用reduce()方法,在rudece()的回调函数的参数部分,_是一个占位符,表示不传任何值,因为这里原本是表当前调用项的下标的参数,而为了通过arr展示出过滤后的数组,且没有无意义的传参,所以使用了占位符。最后通过reduce()计算出了最终的价格。
总结
我在最开始编程涉及到对数组相关的操作时,第一个想到的就是使用for循环,有时碰到难一点的需求,甚至无法下手,归根结底还是自己对数组上面的方法不怎么熟悉,这在开发中是十分吃亏的,有时完成一个需求,可能只需要几行代码,而由于自己知识面不广,最后需要几十行代码去完成。比如filter()的案例,如果使用es6语法去编写,只需一行就可以完成,只是有点长了。。。
代码如下:
let totalPrice = arr.filter( item => item.state === true).reduce( ((previousValue,currentValue) =>previousValue += currentValue.price * currentValue.count),0 )
所以,拓宽自己的知识面是非常重要的,而且这是也必须的!
以上就是今天要讲的内容,本文介绍了遍历数组的部分方法,而对数组的处理还有很多方法等待着我们去学习,我将会在后续的文章中为大家一一展示。如果觉得对你有用就点个赞吧