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循环枚举。
      [完]
  • 相关阅读:
    回溯算法之素数环
    回溯算法之迷宫问题
    回溯算法之0-1背包问题
    贪心算法之搬桌子问题
    贪心算法之背包问题
    动态规划之收集苹果
    动态算法
    c#数和二叉树
    c# 排序算法
    c#栈的习题2
  • 原文地址:https://www.cnblogs.com/weiqinl/p/9572751.html
Copyright © 2011-2022 走看看