javascript使用Object.keys遍曆對象屬性名稱

來源:互聯網
上載者:User


在實際開發中,我們有時需要知道對象的所有屬性,js原生給我們提供了一個很好的方法:Object.keys,該方法返回一個數組

var obj = {  'a':'123',  'b':'345',};console.log(Object.keys(obj));  //['a','b']

 

值得注意的是,如果keys方法裡傳入的是字串,也會返回數組,只是數組裡的值是字串中每個字元的索引:

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

 

例子,遍曆數組和遍曆對象的區別

 

<script>    //----------------for用來遍曆數組對象--    var i,myArr = [1,2,3];    for (var i = 0; i < myArr.length; i++) {        console.log(i+":"+myArr[i]);    };    //---------for-in 用來遍曆非數組對象    var man ={hands:2,legs:2,heads:1};    //為所有的對象添加clone方法,即給內建原型(object,Array,function)增加原型屬性,該方法很強大,也很危險    if(typeof Object.prototype.clone ==="undefined"){        Object.prototype.clone = function(){};        }    //    for(var i in man){        if (man.hasOwnProperty(i)) { //filter,只輸出man的私人屬性            console.log(i,":",man[i]);        };    }    //輸出結果為print hands:2,legs:2,heads:1    for(var i in man) {//不使用過濾        console.log(i,":",man[i]);    }        //輸出結果為    //hands : 2 index.html:20    //legs : 2 index.html:20    //heads : 1 index.html:20    //clone : function (){}     for(var i in man) {        if(Object.prototype.hasOwnProperty.call(man,i)) { //過濾            console.log(i,":",man[i]);        }    }   //輸出結果為print hands:2,legs:2,heads:1</script>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.