代码改变世界

Object.keys()

2013-12-11 11:43  freefei  阅读(473)  评论(0)    收藏  举报
Object.keys 函数 (JavaScript)

 

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

  1. Object.keys(object)
参数
 

参数

定义

object

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

返回值

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

异常

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

备注

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

有关属性的 enumerable 特性的信息,请参见 Object.defineProperty 函数 (JavaScript)和 Object.getOwnPropertyDescriptor 函数 (JavaScript)

 

示例

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

  1. // Create a constructor function.
  2. function Pasta(grain, width, shape) {
  3.     this.grain = grain;
  4.     this.width = width;
  5.     this.shape = shape;
  6.  
  7.     // Define a method.
  8.     this.toString = function () {
  9.         return (this.grain + ", " + this.width + ", " + this.shape);
  10.     }
  11. }
  12.  
  13. // Create an object.
  14. var spaghetti = new Pasta("wheat"0.2"circle");
  15.  
  16. // Put the enumerable properties and methods of the object in an array.
  17. var arr = Object.keys(spaghetti);
  18. document.write (arr);
  19.  
  20. // Output:
  21. // grain,width,shape,toString

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

  1. // Create a constructor function.
  2. function Pasta(grain, width, shape) {
  3.     this.grain = grain;
  4.     this.width = width;
  5.     this.shape = shape;
  6. }
  7.  
  8. var polenta = new Pasta("corn"1"mush");
  9.  
  10. var keys = Object.keys(polenta).filter(CheckKey);
  11. document.write(keys);
  12.  
  13. // Check whether the first character of a string is "g".
  14. function CheckKey(value) {
  15.     var firstChar = value.substr(01);
  16.     if (firstChar.toLowerCase() == "g")
  17.         return true;
  18.     else
  19.         return false;
  20. }
  21.  
  22. // Output:
  23. // grain
@ https://github.com/ranmufei Pop Balloons Game - Free Online Stress Relief Game