1、for in用法
for in遍历数组和对象--不能遍历Map--没有顺序规则
var test1=[{name:'aaa',value:111},{name:'bbb',value:222}] for (let key in test1) { document.write(key+"key是数组下标<br>"); } var test2={name:'aaa',value:111} for (let key in test2) { document.write(key+"key是对象的健名<br>"); }
输出
0key是数组下标
1key是数组下标
namekey是对象的健名
valuekey是对象的健名
2、for of用法
for-of,可以很方便的遍历数组和集合,但是却不能遍历对象
数组遍历
var test1=[{name:'aaa',value:111},{name:'bbb',value:222}] for (let index of test1.keys()) { console.log(index); } // 0 // 1 for (let elem of test1.values()) { console.log(elem); } // {name:'aaa',value:111} // {name:'bbb',value:222} for (let [index, elem] of test1.entries()) { console.log(index, elem); } //0 {name:'aaa',value:111} //1 {name:'bbb',value:222}
Map的遍历
Map.prototype.keys()
:返回键名的遍历器。Map.prototype.values()
:返回键值的遍历器。Map.prototype.entries()
:返回所有成员的遍历器。Map.prototype.forEach()
:遍历 Map 的所有成员。
const map = new Map([ ['F', 'no'], ['T', 'yes'], ]); for (let key of map.keys()) { console.log(key); } // "F" // "T" for (let value of map.values()) { console.log(value); } // "no" // "yes" for (let item of map.entries()) { console.log(item[0], item[1]); } // "F" "no" // "T" "yes" // 或者 for (let [key, value] of map.entries()) { console.log(key, value); } // "F" "no" // "T" "yes" // 等同于使用map.entries() for (let [key, value] of map) { console.log(key, value); } // "F" "no" // "T" "yes"