遍历数组的方法
首先定义一个数组,之后都基于这个数组进行遍历,若有新定义的数组,有详细代码
var list = [{
id: 1,
name: '四川',
type: 'city',
mainCity:'成都'
}, {
id: 2,
name: '上海',
type: 'city',
mainCity:'上海'
}, {
id: 3,
name: '广东',
type: 'city',
mainCity:'深圳'
}, {
id: 4,
name: '云南',
type: 'city',
mainCity:'昆明'
}, {
id: 5,
name: '浙江',
type: 'city',
mainCity:'杭州'
}]
1.some遍历,主要是用于判断是否有元素满足条件,若有一项满足条件则返回true,终止循环
let reselt = this.list.some(item => {
// return item.name
console.log(item.name); //四川、上海、广东、云南、浙江
return item.id >= 3
// console.log(item);
})
console.log(reselt); //true
2.every遍历,若数组中的每一项都满足条件则返回true
var result = this.list.every(item => {
item.id >= 3
console.log(item); //{id: 1, name: '四川', type: 'city', mainCity: '成都'}
})
console.log(result);//false
3.forEach遍历,没有返回值,对原数组没有影响
this.list.forEach(element => {
console.log(element.name);//四川、上海、广东、云南、浙江
});
4.for…of遍历,返回对象,可以使用break、continue和return语句
for (const result of this.list) {
console.log(result);
}
5.for…in遍历,返回数组中的下标
for (const index in this.list) {
console.log(index);//返回数组中的下标
}
6.for循环遍历,打印每一条数组中信息,返回对象
for (i = 0; i <= list.length; i++) {
console.log(list[i]);
//{id: 1, name: '四川', type: 'city', mainCity: '成都'}
}
7.map遍历,返回新数组,不会改变原数组
let newArr = this.list.map(item => {
return item.name
})
console.log(newArr) //['四川', '上海', '广东', '云南', '浙江']
8.filter遍历,不会改变原数组并返回新数组
var newArr = this.list.filter(item => {
return item.id != 1
})
console.log(newArr); // {id: 2, name: '上海', type: 'city', mainCity: '上海'}
9.find遍历,返回数组中符合测试函数条件的第一个元素
var newArr = this.list.find(element => {
return element.type == 'city'
})
console.log(newArr);//{id: 1, name: '四川', type: 'city', mainCity: '成都'}
10.reduce遍历,接收一个函数,该函数有四个参数:上一次的值,当前值,当前值的索引,数组,可用于数组去重,求数组项最大值,求数组项之和
let list = [1, 2, 3, 4, 5, 2, 3];
// 数组去重
let newList = list.reduce(function(prev, cur) {
//判断字符串是否包涵子字符串
if (prev.indexOf(cur) == -1) {
prev.push(cur);
}
return prev;
}, []);
console.log(newList); //[1,2,3,4,5]
// 数组求和
let newList1 = list.reduce((i, j) => {
return i + j;
}, 0);
console.log(newList1) //20
// 求数组中的最大项
let newList2 = list.reduce((pre, cur) => pre > cur ? pre : cur)
//pre=1不大于cur=2,返回2;
//pre接收返回值2;pre=2不大于cur=3,返回3
console.log(newList2)
//输出5,若找最小值:pre<cur?pre:cur
11.findIndex遍历,返回符合条件的数组下标
var newArr = this.list.findIndex(element => {
return element.id == 5
})
console.log(newArr);//4
12.ES6中的keys(),对键名的遍历
for (let index of list.keys()) {
console.log(index);//0、1、2、3、4
}
13.ES6中的values(),对键值的遍历
for (let name of list.values()) {
console.log(name);
//{id: 1, name: '四川', type: 'city', mainCity: '成都'}
}
若有错误 欢迎指出