zoukankan      html  css  js  c++  java
  • js属性对象的propertyIsEnumerable方法

    定义

    每个对象都有一个propertyIsEnumerable()方法。此方法返回一个布尔值,表明指定的属性是否是可枚举。

    This method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. (来源MDN)

    翻译:

    此方法可以确定对象中的指定属性是否可以由for ... in循环枚举,但通过原型链继承的属性除外。

    我理解的意思,不知道对不对:
    此方法,可以确定对象中的指定属性(除了通过原型链继承的属性)是否可以由for...in循环枚举。
    也就是说:
    for...in循环出来的属性,除了通过原型链继承的属性不是可枚举,其他都是可枚举属性。

    用法举例

    使用方法obj.propertyIsEnumerable(prop)来判断是否可枚举。

    const obj = {};
    const arr = [];
    obj.name= 'weiqinl';
    arr[0] = 2018;
    console.log(obj.propertyIsEnumerable('name'));  // true
    console.log(arr.propertyIsEnumerable(0)); // true
    console.log(arr.propertyIsEnumerable('length')); // false
    

    找出对象的可枚举属性

    function Person(name,age) {
        this.name = name
        this.age = age
        this.say = function() {
            console.log('say hi')
        }
    }
    Person.prototype.where = 'beijing' // 在原型链上添加属性
    var p = new Person('weiqinl', 18)  // 实例化一个对象
    p.time = '2018'    // 在实例上添加属性
    let arr = []
    for(let i in p) {
        console.log(i, p.propertyIsEnumerable(i))
        p.propertyIsEnumerable(i)? arr.push(i) : ''
    }
    console.log(arr)
    // name true
    // age true
    // say true
    // time true
    // where false
    // (4) ["name", "age", "say", "time"]
    

    浏览器的window对象的可枚举属性

    window对象的可枚举属性到底有多少个呢?

    var arr = []
    for(let i in window) {
        if(window.propertyIsEnumerable(i)) {
            arr.push(i)
        }
    }
    console.log(arr.length) 
    

    这个长度,在每个网站的值都是不一样的,因为他们会各自往window上添加全局属性。我看到最少的可枚举属性值个数为195

    与hasOwnProperty的区别

    1. hasOwnProperty()方法检验是否为自有属性
    2. propertyIsEnumberable()方法,可以确定对象中的指定属性(除了通过原型链继承的属性)是否可以由for...in循环枚举。
      [完]
  • 相关阅读:
    NSIS实现ArcEngine Runtime安装和自动注册
    .Net平台下开发中文语音应用程序(转载)
    NSIS:判断并安装.NET Framework的例子(转载)
    教你如何将IPHONE恢复正常(转载)
    C# SendMessage WPARAM大全 (收集)
    关于开发WPF的一些感想
    C#版本的CPU性能测试
    ITTC数据挖掘平台介绍(二) 微博数据挖掘和分析
    [XMOVE自主设计的体感方案] XMove 4.0 无线组网协议
    [XMOVE自主设计的体感方案] XMove 4.0节点介绍——抽象节点和硬件
  • 原文地址:https://www.cnblogs.com/weiqinl/p/9572751.html
Copyright © 2011-2022 走看看