1、map: 一定遍历全部数据,不能通过return结束,消耗性能,不要常用。
// 返回一个经过处理后的新数组,但不改变原数组的值。
var a = [1,2,3,4,5]
var b = a.map((item) => {
return item = item * 2
})
console.log(a) // [1,2,3,4,5]
console.log(b) // [2,4,6,8,10]
//map中可改变原数组的情况和原理与forEach相同
2、forEach: 遍历全部数据,不能通过return结束循环,消耗性能
用于不转换数据的全部遍历。
//1、没有返回值
var a = [1,2,3,4,5]
var b = a.forEach((item) => {
})
console.log(b)
// undefiined
//2、原数组并没有发生改变
var a = [1,2,3,4,5]
a.forEach((item, index, arr) => {
item = 2
})
console.log(a)
//[1,2,3,4,5]
//3、修改item的值,依然没有修改原数组。
var a = [1,'1',{num:1},true]
a.forEach((item, index, arr) => {
item.num = 2
item = 2
})
console.log(a)
// [1,'1',{num:2},true]
//4、当修改数组中对象的某个属性时,发现属性改变了。
var a = [1,2,3,4,5]
a.forEach((item, index, arr) => {
arr[index] = item * 2
})
console.log(a)
// [2,4,6,8,10]
3、for循环:通过累加数组索引,来输出数组中的值,一般只用于循环数组。有下标,通过下标取值,可通过return退出循环。
4、for of :for of 循环对象是数组 [{}],遍历时获得其中的每一项(属性值),可以通过return结束循环,但是循环的时候没有下标。
5、for in: 不但可以遍历数组,还可以遍历对象,数组遍历下标,对象遍历属性。
var arr = [11,22,33];
var obj = {
name: '张三',
age: 17,
action: {
123: '123',
456: '456'
}
}
for(let i in arr){console.log(i)} // 打印:0,1,2
for(let i in obj){console.log(i)} // 打印:name,age,action
for(let i of arr){console.log(i)} // 打印:11,22,33
for(let i of obj){console.log(i)} // 报错:Uncaught TypeError: obj1 is not iterable
异步问题
即如果在使用遍历数组时,内有异步操作,那么后面的代码执行是不会等待的执行结果。我们需要加async await方法。
//使用forEach,没等接口返回数据就进行下一步了
this.ipList=[]
this.checkedList.forEach(item=>{
api.selectCode({code:item}).then(res=>{
if(res.data.reply.returnCode.type!="S") return this.$message.error(res.data.reply.returnCode.message)
let list=res.data.reply.result.list
list.forEach(val=>{
this.ipList.push(val)
})
})
})
// 解决方式
this.ipList=[]
const promise=this.checkedList.map(item=>{
return new Promise((resolve,reject)=>{
api.selectCode({code:item}).then(res=>{
if(res.data.reply.returnCode.type!="S") return this.$message.error(res.data.reply.returnCode.message)
let list=res.data.reply.result.list
list.forEach(val=>{
this.ipList.push(val)
})
resolve(res)
}).catch(error=>reject(error))
})
})
const res=await Promise.all(promise)
// 如果是数组可以用for of方式
async getTask(){
for (const item of lists) {
await getTask().then(res => {
this.data = res.data
})
}
}