Object.keys 函数 (JavaScript)
参数
|
参数
|
定义
|
|
object
|
必需。 包含属性和方法的对象。 这可以是您创建的对象或现有文档对象模型 (DOM) 对象。
|
异常
如果为 object 参数提供的值不是对象的名称,则将引发 TypeError 异常。
示例
下面的示例创建一个对象,该对象具有三个属性和一个方法。 然后使用 keys 方法获取该对象的属性和方法。
- function Pasta(grain, width, shape) {
- this.grain = grain;
- this.width = width;
- this.shape = shape;
-
-
- this.toString = function () {
- return (this.grain + ", " + this.width + ", " + this.shape);
- }
- }
-
- var spaghetti = new Pasta("wheat", 0.2, "circle");
-
- var arr = Object.keys(spaghetti);
- document.write (arr);
-
下面的示例显示 Pasta 对象中以字母“g”开头的所有可枚举属性的名称。
- 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);
-
- function CheckKey(value) {
- var firstChar = value.substr(0, 1);
- if (firstChar.toLowerCase() == "g")
- return true;
- else
- return false;
- }
-