js知識點 js怎么遍歷數(shù)組中的對象的屬性?
js怎么遍歷數(shù)組中的對象的屬性?具體代碼如下所示: ;1、<script> //----------------for用來遍歷數(shù)組對象;2、 var i,myArr = [1,2,3]
js怎么遍歷數(shù)組中的對象的屬性?
具體代碼如下所示: ;1、<script> //----------------for用來遍歷數(shù)組對象;2、 var i,myArr = [1,2,3] for (var i = 0 i < myArr.length i ) { console.log(i ":" myArr[i]) } ;3、 //---------for-in 用來遍歷非數(shù)組對象 var man ={hands:2,legs:2,heads:1} //為所有的對象添加clone方法,即給內(nèi)置原型(object,Array,function)增加原型屬性,該方法很強大,也很危險 if(typeof Object.prototype.clone ==="undefined"){ Object.prototype.clone = function(){} } ;4、 // for(var i in man){ if (man.hasOwnProperty(i)) { //filter,只輸出man的私有屬性 console.log(i,":",man[i]) } } ; ;5、//輸出結(jié)果為print hands:2,legs:2,heads:1 for(var i in man) {//不使用過濾 console.log(i,":",man[i]) } ;6、 //輸出結(jié)果為://hands : 2 index.html:20 //legs : 2 index.html:20 //heads : 1 index.html:20 //clone : function ;7、for(var i in man) { if(Object.prototype.hasOwnProperty.call(man,i)) { //過濾 console.log(i,":",man[i]) } };8、 //輸出結(jié)果為print hands:2,legs:2,heads:1 </script> 。
js/jQuery如何按順序遍歷JSON?
這和各瀏覽器的Map鍵名的遍歷方法相關(guān),jquery只不過是包裝了一下 for (key in obj)。解決方法為將鍵名放入的數(shù)組,通過遍歷數(shù)組的方式就不會有問題了。var a = []$.each(obj, function(key, val) { a[a.length] = key })a.sort()$.each(a, function(i, key) { window.alert("key = " obj[key]) // 訪問JSON對象屬性})