for in 和 for of
const obj = {name: 'mali'}
cosnt arr = [1, 2, 3]
- for in,遍历结果key是属性名;
- for of,遍历结果value是属性值;
- 不能遍历对象;for of 的要求是 interable;
for in 和 Object.keys()
const obj = {name: 'mali'}
obj.__proto__.test = 'test'
- for in 会遍历出自身和原型可枚举属性;
- Objec.keys()只返回自身可枚举属性组成的数组;
使用for in 一般我们都会搭配Object.hasOwnProperty()
const obj = {name: 'mali'}
obj.__proto__.test = 'test'
for (key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(key);
}
}