JavaScript中存在着不少循环的方法jquery
常见的有for,while,do while,for in等,web
ES5中的forEach,数组
ES6的for of ,数据结构
jquery中封装的eachsvg
局限性很大,经过累加数组索引,来输出数组中的值。通常用来遍历数组,不能遍历对象,由于对象的长度是undefined,没法做为其循环的条件。函数
let person = { name1:"fur", age:"1", hobbies:{ study:"code", play:"games" } } let arr = ['fur','furfur','furfur-jiang'] console.log("遍历对象结果:") console.log("person对象长度= "+person.length) console.log("遍历数组结果:") for(let i = 0 ; i < arr.length ; i++){ console.log(arr[i]) }
for - 循环代码块必定的次数 while - 当指定的条件为 true 时循环指定的代码块 do/while - 一样当指定的条件为 true 时循环指定的代码块
for…in 循环将遍历对象的全部可枚举属性。不但能够循环遍历数组,还能够循环遍历对象。this
for (let index in Object) { // }
let person = { name1:"fur", age:"1", hobbies:{ study:"code", play:"games" } } let arr = ['fur','furfur','furfur-jiang'] //遍历对象 console.log("遍历对象结果:") for (let i in person) { if(person[i] instanceof Object){ for (let j in person[i]){ console.log(person[i][j]) } }else{ console.log(person[i]) } } //遍历数组 console.log("遍历数组结果:") for (let i in arr) { console.log(arr[i]) }
forEach() 方法用于调用数组的每一个元素,并将元素传递给回调函数。可经过参数直接获取到值,其中item为该索引下的值,index为索引,arr为数组自己,参数名可改变,可是顺序不能改变。spa
注意:code
forEach() 对于空数组是不会执行回调函数的。xml
不能遍历对象
array.forEach(function(item, index, arr), thisValue)
参数 | 描述 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。当前元素所属的数组对象。 |
let arr = ['fur','furfur','furfur-jiang'] //遍历数组 console.log("遍历数组结果:") arr.forEach(function(item, index, arr){ console.log(item) console.log(index) console.log(arr) })
for...of
语句建立一个循环来迭代可迭代的对象。ES6新增的方法,可是缺点是没法遍历自定义普通对象。
for...of
容许你遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合),TypedArray,函数的 arguments 对象,NodeList 对象等可迭代的数据结构等。
for (variable of iterable) { statement }
let arr = ['fur','furfur','furfur-jiang'] //遍历数组 console.log("遍历数组结果:") for (let item of arr){ console.log(item) }
Set 和 Map 结构
Set 结构遍历时,返回的是一个值,而 Map 结构遍历时,返回的是一个数组,该数组的两个成员分别为当前 Map 成员的键名和键值。
let map = new Map() map.set("name1","fur") map.set("name2","furfur") map.set("name3","furfur-jiang") // 也能够这样链式定义 //let map = new Map().set("name1","fur").set("name2","furfur").set("name3","furfur-jiang") console.log("Set结构遍历:") for(let [key,value] of map) { console.log(key +'.'+ value) } console.log("Map结构遍历:") for(let i of map){ console.log(i) }
jquery下的each方法有两种:
一种为$(’ ').each(),是搭配jq选择器遍历jquery对象获取页面元素的方法。
一种为$.each()循环方法,用于循环遍历数组、对象。
注意:用这个方法须要导入jq的包,each与forEach的item和index放置位置相反哦!
let person = { name1:"fur", age:"1", hobbies:{ study:"code", play:"games" } } let arr = ['fur','furfur','furfur-jiang'] //遍历对象 console.log("遍历对象结果:") $.each(person,function(index,item){ if(item instanceof Object){ $.each(item,function(index,item){ console.log(index+'.'+item) }) }else{ console.log(index+'.'+item) } }) //遍历数组 console.log("遍历数组结果:") $.each(arr,function(index,item){ console.log(index+'.'+item) })
码字不易,有用的话点个赞呀!谢谢