javascript 遍歷陣列物件
阿新 • • 發佈:2018-12-13
陣列物件
var arr = ["value1","value2","value3"];
var obj = {
aa:"value1",
bb:"value2",
cc:function(){
console.log("value3")
}
}
原生方法
//for in 遍歷陣列 for(var i;i<arr.lengt;i++) { consle.log(i+":"+arr[i]); } //for in 遍歷陣列 ,物件 for(var i in obj) { console.log(i+':'+obj[i]); } //foreach 遍歷陣列,三個引數依次是陣列元素,索引,陣列本身 arr.foreach(function(value,index,array){ console.log(value+','+index+','+array[index]); }) #注意,for-in、for能正確響應break、continue、return語句,但是 foreach不行
for-of
#for...of語句在可迭代物件(包括 Array, Map, Set, String, TypedArray,arguments 物件等等)上建立一個迭代迴圈,對每個不同屬性的屬性值,呼叫一個自定義的有執行語句的迭代掛鉤 //for-of遍歷陣列,不帶索引,i即為陣列元素 for(let i of arr){ console.log(i);//列印的出來的就是值 } //輸出 "value1" "value2" "value3" // for-of遍歷Map物件 let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]); for (let [key, value] of iterable) { console.log(value); } //輸出 1 2 3 // for-of遍歷字串 let iterable = "china中國"; for (let value of iterable) { console.log(value); } //輸出 "c" "h" "i" "n" "a" "中" "國"
Object.keys()
#js有原生的Object.keys()方法(低版本IE不相容),返回一個由物件的可列舉屬性名組成的陣列 /****Object.keys()返回鍵名陣列****/ //陣列型別 let arr = ["a", "b", "c"]; console.log(Object.keys(arr)); // (3) ['0', '1', '2'] // 類陣列物件 let anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.keys(anObj)); // (3) ['2', '7', '100'] //一般物件 let xyz = {z: "zzz", x: "xxx", y: "yyy"}; console.log(Object.keys(xyz)); // (3) ["z", "x", "y"]
javascript原生遍歷方法的建議用法:
用for迴圈遍歷陣列
用for-in遍歷物件
用for-of遍歷類陣列物件(ES6)
用Object.keys()獲取物件屬性名的集合