for in
for in 使用于可枚舉的數(shù)據(jù) 如 對象 數(shù)組 字符串
什么是可枚舉的:屬性的enumerable值為true,表示可枚舉
可以通過es7新增的屬性 Object.getOwnPropertyDescriptors()驗證 查看
Object.getOwnPropertyDescriptor() 方法用于 返回 指定 對象 上一個自有 屬性 對應(yīng)的屬性描述符
// 通過Object.getOwnPropertyDescriptors()
const a = [1, 23, 3]
console.log(Object.getOwnPropertyDescriptors(a));
const b = { a: 1, b: 2 }
console.log(Object.getOwnPropertyDescriptors(b));
const c = 'string'
console.log(Object.getOwnPropertyDescriptors(c));
看下圖打印的信息,enumerable值為true表示都是可迭代對象
for in 不僅能便利自身的屬性,他還能便利原型鏈上可枚舉的屬性
他返回的是key的值,并且不能保證順序
let a = [1,2,3]
Array.prototype.num = 4
for(let i in a){
console.log(i) // 0,1,2,num
console.log(a[i]) // 1,2,3,4
}
// 他返回的是value的值
for(let j of a){
console.log(j) // 1,2,3
}
for of
for of 適用于可迭代數(shù)據(jù)
什么是可迭代數(shù)據(jù) :在原型鏈上具有Symbol.iterator屬性,通過調(diào)用.next() 方法,返回對應(yīng)的屬性
可迭代數(shù)據(jù):array string Map Set 函數(shù)的arguments對象 還有我們的生成器函數(shù)function*( ){ }文章來源:http://www.zghlxwxcb.cn/news/detail-470988.html
const a = [1,2,3]
//a.prototype上有這么一個屬性 Symbol(Symbol.iterator):? values() 表示可迭代的
同理 string Map Set 這些原型上都有這個屬性
for of 只能便利自身的屬性
他得到的是value 具體和迭代器的內(nèi)部實現(xiàn)有關(guān)文章來源地址http://www.zghlxwxcb.cn/news/detail-470988.html
const arr = [1, 2, 3]
arr[Symbol.iterator] = function () {
const that = this
return {
i: 0,
next() {
// 正常的 通過 for of 返回value
return this.i < that.length ? { value: that[this.i++], done: false } : { value: undefined, done: true }
}
}
}
for (let i of arr) {
console.log(i); // 1,2,3
}
// 改寫Symbol.iterator的next方法
arr[Symbol.iterator] = function () {
const that = this
return {
i: 0,
next() {
// 通過改寫之后 for of也能返回key
return this.i < that.length ? { value: this.i++, done: false } : { value: undefined, done: true }
}
}
}
for (let i of arr) {
console.log(i); // 0,1,2 輸出的是key
}
到了這里,關(guān)于for in和for of的區(qū)別的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!