美文网首页
Object.keys详解

Object.keys详解

作者: Allan要做活神仙 | 来源:发表于2017-04-26 11:22 被阅读51次

    实际开发中,有时候需要知道对象的所有属性,原生js提供了一个很好的方法:

    Object.keys(),该方法返回一个数组

    传入对象,返回属性名

    var obj = {
            'a':'123',
            'b':'345'
    };
    console.log(Object.keys(obj));  //['a','b']
    var obj1 = { 
            100: "a", 
            2: "b", 
            7: "c"
    };
    console.log(Object.keys(obj1)); // console: ["2", "7", "100"]
    

    传入字符串,返回索引

    var str = 'ab1234';
    console.log(Object.keys(obj));  //[0,1,2,3,4,5]
    

    构造函数 返回空数组或者属性名

    function Pasta(name, age, gender) {
                this.name = name;
                this.age = age;
                this.gender = gender;
                this.toString = function () {
                        return (this.name + ", " + this.age + ", " + this.gender);
                }
        }
    
        console.log(Object.keys(Pasta)); //console: []
    
        var spaghetti = new Pasta("Tom", 20, "male");
        console.log(Object.keys(spaghetti)); //console: ["name", "age", "gender", "toString"]
    

    数组 返回索引

        var arr = ["a", "b", "c"];
        console.log(Object.keys(arr)); // console: ["0", "1", "2"]
    

    相关文章

      网友评论

          本文标题:Object.keys详解

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