最先的循環方式javascript
var a = ["a", "b", "c"]; for(var index = 0;index < a.length;index++){ console.log(a[index]); }
ES5
的 forEach
java
var a = ["a", "b", "c"]; a.forEach(function(element) { console.log(element); });
forEach雖然簡潔了很多,可是不能使用break
,continues
,return
for..in
也能夠遍歷數組編程
var a = ["a", "b", "c"]; for(var index in a){ // console.log(a[index]); console.log(typeof index); }
這是一個糟糕的選擇!數組
賦值給index並非一個數字,而是一個
String
,可能無心進行字符串計算,這給編程帶來不便設計
- 做用於數組的
for-in
循環除了遍歷數組元素之外,還會遍歷自定義屬性,舉個例子,若是你的數組中有一個可枚舉的類型a.name,那麼循環將額外執行一次,遍歷到名爲name的索引,甚至數組原型鏈上的屬性都能被訪問到- 這段代碼可能按照 隨機順序遍歷數組
for-in
這個代碼是爲普通對象設計的,不適用於數組的遍歷
因此平時咱們最好不要使用for-in遍歷數組
主角登場: for...ofcode
var a = ["a", "b", "c"]; for(var value of a){ console.log("for of:"+value); }
這個方法是最簡潔的,而且修復了for-in
循環的全部缺點,與forEach()
不一樣的是,它能夠正確的響應break
,contine
,return
語句注意: for-of循環不支持普通對象,可是若是你想迭代一個對象的屬性,能夠使用
for-in
循環(這也是它的本職工做)或者內建的Object.keys()
方法對象
var student={ name:'wujunchuan', age:22, locate:{ country:'china', city:'xiamen', school:'XMUT' } } for(var key of Object.keys(student)){ //使用Object.keys()方法獲取對象key的數組 console.log(key+": "+student[key]); }
與其說使用Object.keys()
還不如使用for-in
for(var prop in student){ console.log(prop+': '+student[prop]); }