for ... in ...
- 以任意顺序遍历一个对象的除Symbol以外的可枚举属性。
- key不同的属性名,string类型
- 不建议与数组一起使用,数组可以用Array.prototype.forEach()和for ... of
- 判断是不是实例上的属性 key in object && object.hasOwnProperty(key)
const s = Symbol('c')
var Test = function Test () {
this.a = 1
this[s] = 3
}
Test.prototype.a = function () {}
Test.prototype.getA = function () {
}
let test = new Test
Object.defineProperty(test, 'b', {
configurable: true,
enumerable: false,
value: 2
})
for (let i in test) {
console.log(i) // a getA
}
判断是否在原型上
'a' in test // true
test.hasOwnProperty('a') // true
Object.getOwnPropertySymbols(test) // [Symbol(c)]
'a' in test && test.hasOwnProperty('a') // true 是实例属性
'getA' in test // true
test.hasOwnProperty('getA') // false
'getA' in test && !test.hasOwnProperty('getA') // true 是原型属性
Object.keys
- 方法会返回一个由一个给定对象的自身可枚举属性组成的数组
- 数组中属性名的排列顺序和使用 for...in 循环遍历该对象时返回的顺序一致
- 不包括原型属性和Symbol
const s = Symbol('c')
var Test = function Test () {
this.a = 1
this[s] = 3
}
Test.prototype.a = function () {}
Test.prototype.getA = function () {
}
let test = new Test
Object.defineProperty(test, 'b', {
configurable: true,
enumerable: false,
value: 2
})
Object.keys(test).forEach(item => console.log(item)) // a
Object.getOwnPropertyNames(test) // ['a', 'b']
只返回不可枚举的属性
let enumNoenums = Object.getOwnPropertyNames(test) // 属性(不包括Symbol和原型属性)
let enums = Object.keys(test) // 可枚举属性
enumNoenums.filter(item => !enums.includes(item)) // 不可枚举属性
for ... of ...
- 在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
const str = '123456'
for (let i of str) {
console.log(i) // 1 2 3 4 5 6
}
const arr = [1, 2, 3]
for (let i of arr) {
console.log(i) // 1 2 3
}
const set = new Set([4, 5, 6])
for (let i of set) {
console.log(i) // 4 5 6
}
const map = new Map([['a', 7], ['b', 8], ['c', 9]])
for (let i of map) {
console.log(i) // ['a', 7] ['b', 8] ['c', 9]
}
const fun = function () {
for (let args of arguments) {
console.log(args)
}
}
fun(1, 2, 3, [1, 2, 3]) // 1 2 3 [1, 2, 3]
总结
- for...in 语句以任意顺序迭代对象的可枚举属性(不包括Symbol)。
- Object.keys 语句迭代对象定义的可枚举属性(不包括Symbol和原型)
- for...of 语句遍历可迭代对象定义要迭代的数据。
MDN FOR IN
MDN OBJECT.KEYS
MDN FOR OF
for in,Object.keys,for of 的区别
JavaScript里的循环方法:forEach,for…in,for…of
欢迎大佬star