for...in...
-
for...in...
以任意顺序迭代一个对象(除了Symbol对象)的可枚举属性,包括继承来的可枚举属性 -
for in是ES5标准,遍历key
-
语法
for (variable in object){}
variable
:在每次迭代时,variable会被赋值为不同的属性名object
:非Symbol类型的可枚举属性被迭代的对象
在Array数组中的使用
-
for...in...
不适合用于遍历一个关注索引顺序的数组-
原因:
- 遍历得到的index索引是字符串类型而不是number类型,不能直接进行几何运算
let myArray = [1, 2, 10, 30, 100]; for (const index in myArray) { console.log(typeof index); }
- 遍历顺序有可能不是按照实际数组的内部顺序(可能按照随机顺序)
for...in...
会遍历数组所有可枚举属性,包括从原型继承来的,需要配合hasOwnProperty()
方法判断某个属性是否是该对象的实例属性,来将从原型继承的对象从循环中剔除
let myArray = [1, 2, 10, 30, 100]; Array.prototype.name = 'world'; myArray.type='数组'; for(let index in myArray){ console.log(index); }
let myArray = [1, 2, 10, 30, 100]; Array.prototype.name = 'world'; myArray.type='数组'; for(let index in myArray){ if (myArray.hasOwnProperty(index)) { console.log(index); } }
-
在对象中的使用
-
for ... in
就是为遍历对象属性而构建的 -
for(variable in object)
variable
为object的键名
var obj = {a:1, b:2, c:3}; for (var key in obj) { console.log('key:',key); console.log('value:',obj[key]); }
-
遍历对象同样会继承原型的属性,如果想要只遍历自身的属性,可以使用
hasOwnProperty
let obj = { name: 'xiaoming', age: 18 }; for (const key in obj) { if (obj.hasOwnProperty(key)) { console.log(key) // name,age } }
遍历字符串String类型数据
-
for(variable in string)
variable
为string每个字符对应的索引号
let str = 'hello'; for (let key in str) { console.log(key); }
-
同样可以使用
hasOwnProperty
过滤掉从原型继承来的属性
for...of...
-
用于遍历可迭代对象(包括
Array
,Map
,Set
,String
,TypedArray
,arguments 对象等等) -
for of是ES6标准,遍历valu
-
语法:
for (variable of iterable) { //statements }
variable
:iterable的值iterable
:可迭代对象
-
遍历数组、字符串等等时,variable都是对应的值,并不是值的索引
-
在遍历
Map
,variable
可以是一个数组,有两个内容key
:子元素的键值value
:子元素的值
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]); for (const [key,value] of iterable) { console.log('key:', key); console.log('value:', value); }
只有一个内容时
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]); for (const item of iterable) { console.log(item); }
- 其他对于数组、字符串等的示例可以参考MDN,上面标注的都很详细