1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 <body> 8 <!-- 这几种数据格式都可以用for循环来遍历,for...of也都可以遍历绝大多数的数据结构 --> 9 <script type="text/javascript"> 10 let a = [ 11 { 12 name:'张三', 13 age:'23', 14 address:'郑州' 15 }, 16 { 17 name:'李四', 18 age:'24', 19 address:'北京' 20 }, 21 { 22 name:'王五', 23 age:'25', 24 address:'这是数组对象' 25 }, 26 ] 27 28 for (let item in a) { //打印的item为数组的索引:0、1、2 29 console.log(item) 30 } 31 for (let item of a) {//等同于上一个的console.log(a[item]) 32 console.log(item)//{name: "张三", age: "23", address: "郑州"} 33 for (let key in item) { //遍历数组中的对象 34 console.log(item[key]) 35 } 36 } 37 a.forEach(item => { //同上 38 console.log(item)//{name: "张三", age: "23", address: "郑州"} 39 }) 40 41 42 let b = ['b','1',1,2,'这是数组'] 43 44 for (let item in b) { //打印的item为数组的索引:0、1、2、3、4 45 console.log(item) 46 } 47 for (let item of b) { 48 console.log(item) 49 } 50 b.forEach(item => { 51 console.log(item) 52 }) 53 54 let c = { 55 key:'object', 56 value:'这是对象' 57 } 58 59 for (let item in c) {//打印的item为对象的key:key、value 60 console.log(item) 61 } 62 // c.forEach(item => {//对象不能使用forEach 63 // console.log(item) 64 // }) 65 // for (let item of c.keys()) {//对象不能直接使用of来遍历 66 // console.log(item) 67 // } 68 69 // 需要添加下面这一句话后对象才可以使用of遍历 70 //或者直接Object.keys()、Object.values()、Object.entries() 71 let {keys, values, entries} = Object 72 73 for (let item of keys(c)) { 74 console.log(item) 75 } 76 for (let item of values(c)) { 77 console.log(item) 78 } 79 for (let item of entries(c)) { 80 console.log(item) 81 } 82 83 let d = { 84 name:[ 85 '张三','李四','王五','这是对象数组' 86 ], 87 age:[ 88 20,21,22,23 89 ] 90 } 91 for (let item of values(d)) { 92 console.log(item)//获取到数组 93 item.forEach(items => { 94 console.log(items) //遍历对象中的数组 95 }) 96 } 97 </script> 98 </body> 99 </html>