在大前端领域上,有了前端分离后,使用接口调用数据的情况下,少不了对数组的处理,今天为大家带来js数组中最常见几种处理方式
forEach()
用法:用于调用数组的每个元素,并将元素传递给回调函数。
let ages = [22, 33, 16, 40];
(function myFunction() {
ages.forEach(function(item,index,array){
array[index] = item * 2
})
console.log(ages) //[44, 66, 32, 80]
})()
复制代码
map()
用法:返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值,按照原始数组元素顺序依次处理元素。
let ages = [22, 33, 16, 40];
(function myFunction() {
let map = ages.map(function(item,index,array){
return item * 2
})
console.log(map)
})()
复制代码
map与forEach的区别:
相同点:都是遍历数组的每一项,也都支持三个参数,分别是item(每一项),index(索引值),array(原数组)。什么需求就用哪个参数。
不同点:foreach调用每一个项,再将值传回给回调函数,没有return。map方法在设定好条件后,会返回一个新的数组。
filter()
用法:创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
优势:不会改变原始数组。
let ages = [22, 33, 16, 40];
(function myFunction() {
const a = ages.filter(function(item){
return item > 25
});
console.log(a) //[33,40]
})()
复制代码
some()
用法:检测数组中的元素某一项是否满足指定条件,return一个布尔值,满足即是true,否则为false。
let ages = [22, 33, 16, 40];
(function myFunction() {
let isSome = ages.some(function(item,index,array){
return item > 35
})
console.log(isSome) //true
})()
复制代码
every()
用法和some()非常相似,都可支持三个参数,
let ages = [22, 33, 16, 40];
(function myFunction() {
let isSome = ages.every(function(item,index,array){
return item > 35
})
console.log(isSome)
})()
复制代码
some()和every()的不同点:
some()方法遍历数组,当数组的其中一项满足条件,即返回true,则返回false。
every()方法遍历数组,当数组的每一项都满足条件,才返回true,不全部为true为false。
For循环
最后讲讲最最常见的for循环吧,在for里定义这个a还是建议用let,用var会使内存泄露。
for循环多次遍历代码块,当条件不成立,停止继续循环,可与原文第一个Foreach进行对比。
let ages = [22, 33, 16, 40];
(function myFunction() {
for(let a = 0;a < ages.length;a++){
console.log(ages[a])
}
})()
复制代码