JS 之keys()

The Object.keys() method returns an array of the names of the enumerable properties and methods of an object.

Syntax

Object.keys(object)

Object.keys(object)
object : Required. The object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.

Return Value

An array that contains the names of the enumerable properties and methods of the object.

Examples

 var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // ['2', '7', '100']
// getFoo is property which isn't enumerable
var myObj = Object.create({}, {
  getFoo: {
    value: function () { return this.foo; }
  } 
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

// 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  
// 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() == "g")  
        return true;  
    else  
        return false;  
}  
// Output:  
// grain  

ES6新语法(oh, 老语法...),简单,就是需要了解并记忆,这以后会常用~ 晚安!~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在上一篇帖子里实现了一个立方体的效果,点这里可以看到。源码在这里可以看到可是在最后发现ios下的效果不符合预期。这...
    招展君阅读 11,810评论 0 0
  • 日晷沿着岁月流经的河流,行走梦,趁着夜色开始回溯,那古老的静谧展开被见证,被沉埋的风霜 错过是孤悲永恒的同谋春花秋...
    李瑞祥阅读 5,055评论 13 23
  • 前世情,今生恨。今生恨,来世爱。何来缘定三生,不过老天开的莫大玩笑罢了。
    Nemesis涅墨西斯阅读 1,121评论 0 0
  • 大一的时候去东北,原先的目的地并没有哈尔滨,只是想着到长春去看一看朋友。八天的旅行被分成两半,到长春后才开始计划后...
    咖啡罐不见了阅读 2,642评论 4 2

友情链接更多精彩内容