美文网首页
JS 之keys()

JS 之keys()

作者: 竹剑道 | 来源:发表于2017-07-09 22:52 被阅读16次

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, 老语法...),简单,就是需要了解并记忆,这以后会常用~ 晚安!~

相关文章

网友评论

      本文标题:JS 之keys()

      本文链接:https://www.haomeiwen.com/subject/kfmehxtx.html