zoukankan      html  css  js  c++  java
  • javascript 高级程序设计:深入理解Object.keys 函数

    深入理解Object.keys 函数


     

    该函数是ECMAScript5 Object的新属性方法

    返回对象可枚举属性方法的名称

    Object.keys(object)

    1、参数

    参数

    定义

    object

    必需。 包含属性和方法的对象。 这可以是您创建的对象或现有文档对象模型 (DOM) 对象。

    2、返回值

    一个数组,其中包含对象的可枚举属性和方法的名称。

    3、异常

    如果为 object 参数提供的值不是对象的名称,则将引发 TypeError 异常。

    4、备注

    keys 方法仅返回可枚举属性和方法的名称。 若要返回可枚举的和不可枚举的属性和方法的名称,可使用Object.getOwnPropertyNames

    示例1

    var obj ={x:1,y:2};
    
    var arr =Object.keys(obj);//返回一个数组 [‘x’,’y’];

    示例2

    下面的示例2创建一个对象,该对象具有三个属性和一个方法。 然后使用 keys 方法获取该对象的属性和方法。

    JavaScript

    // Create a constructor function.
    
    function Pasta(grain, width, shape) {
    
        this.grain = grain;
    
        this.width = width;
    
        this.shape = shape;
    
     
    
        // Define a method.
    
        this.toString = function () {
    
            return (this.grain + ", " + this.width + ", " + this.shape);
    
        }
    
    }
    
     
    
    // Create an object.
    
    var spaghetti = new Pasta("wheat", 0.2, "circle");
    
     
    
    // Put the enumerable properties and methods of the object in an array.
    
    var arr = Object.keys(spaghetti);
    
    document.write (arr);
    
     
    
    // Output:
    
    // grain,width,shape,toString

    下面的示例显示 Pasta 对象中以字母“g”开头的所有可枚举属性的名称。

    JavaScript

    // Create a constructor function.
    
    function Pasta(grain, width, shape) {
    
        this.grain = grain;
    
        this.width = width;
    
        this.shape = shape;
    
    }
    
     
    
    var polenta = new Pasta("corn", 1, "mush");
    
     
    
    var keys = Object.keys(polenta).filter(CheckKey);
    
    document.write(keys);
    
     
    
    // Check whether the first character of a string is "g".
    
    function CheckKey(value) {
    
        var firstChar = value.substr(0, 1);
    
        if (firstChar.toLowerCase() == "w")
    
            return true;
    
        else
    
            return false;
    
    }
    
     
    
    // Output:
    
    // width

     

     

  • 相关阅读:
    Openjudge-计算概论(A)-求出e的值
    Openjudge-计算概论(A)-球弹跳高度的计算
    Openjudge-计算概论(A)-求分数序列和
    Openjudge-计算概论(A)-第二个重复出现的数
    Openjudge-计算概论(A)-角谷猜想
    Openjudge-计算概论(A)-分数求和
    Openjudge-计算概论(A)-人民币支付
    Openjudge-计算概论(A)-年龄与疾病
    Openjudge-计算概论(A)-求特殊自然数
    Openjudge-计算概论(A)-短信计费
  • 原文地址:https://www.cnblogs.com/alplcx/p/4221660.html
Copyright © 2011-2022 走看看