我们在项目中用的是相当多的,对数组的处理遍历,循环。
总之与我们形影不离。
今天咱就加深下印象。
1.foreach arr.foreach(item,i)=>{}
对数组的每一个元素执行一次提供的函数(不能使用return、break等中断循环),不改变原数组,无返回值undefined
遍历出数组的每一项值,比如我们要同时用到item以及索引,
this.getChildList.forEach((item, i) => {
if (item.HealthRecordNumber == row.HealthRecordNumber) {
/* console.log(this.numbers.indexOf(i)) */
if (this.numbers.indexOf(i) == -1) {
this.numbers.push(i)
} else {
this.numbers.splice(this.numbers.indexOf(i), 1)
}
}
})
2.fou of (fou item of arr)
es6中的新语法,对数组中的每一项值遍历循环
!!!谨记fou of 不能对普通的对象进行循环,
let arr = ['a', 'b', 'c']
for (let o of arr) {
console.log(o) //a, b, c
}
3.fou in (for index in arr)
循环遍历的值都是数据结构的键值(属性值)
let obj = {l: '1', o: '2', v: '3', e: '4'}
for (let o in obj) {
console.log(o) //遍历的实际上是对象的属性名称 l,o,v,e
console.log(obj[o]) //这个才是属性对应的值1,2,3,4
}
4.我们最最原始的fou循环,自打代码诞生他就存在了,
遍历数组,我们初始的,数组的排序,去重,九九乘法表,等都是用的这个
for循环中可以使用return、break等来中断循环
var arr = [1,2,3,4]
for(var i = 0 ; i< arr.length ; i++){
console.log(arr[i])
}