在實際開發中,我們有時需要知道對象的所有屬性,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>