首页 > 其他分享 >for...in循环

for...in循环

时间:2022-11-05 22:35:13浏览次数:33  
标签:... testProtoType obj log 循环 key console const

/* 
    1.以任意顺序迭代一个对象的可枚举属性(除symbol),包括继承的可枚举属性
    2.主要目的是为了遍历对象的属性存在,不建议和数组一起使用
    3.for (variable in object)
    // 4.循环中断的方法:break;continue;return(需要在函数中使用)
*/

// 1.遍历一个带有symbol的对象
const obj = {
    a: 'a',
    b: 'b',
    c: 'c',
    [Symbol('a')]: "我是symbol"
}

for (const key in obj) {
    console.log("obj." + key + " = " + obj[key]);
}
console.log("=====================================");

// 2.遍历一个带有不可枚举的对象
Object.defineProperty(obj, 'enumerableTrue', {
    value: '可枚举',
    enumerable: true
})
Object.defineProperty(obj, 'notEnumerableTrue', {
    value: '不可枚举',
    enumerable: false
})
for (const key in obj) {
    console.log("obj." + key + " = " + obj[key]);
}
console.log("=====================================");

// 3.继承的枚举
function TestProtoType() {
    this.name = '继承的枚举';
}
TestProtoType.prototype = obj; // 将原型绑定到obj对象
const testProtoType = new TestProtoType();
for (const key in testProtoType) {
    console.log("testProtoType." + key + " = " + testProtoType[key]);
}
console.log("---------------------------------------");
for (const key in testProtoType) {
    // 本身的属性
    if (Object.hasOwnProperty.call(testProtoType, key)) {
        console.log("testProtoType." + key + " = " + testProtoType[key]);
    }
}

 

标签:...,testProtoType,obj,log,循环,key,console,const
From: https://www.cnblogs.com/DEYI-L/p/16861531.html

相关文章