方式一: 使用Javascript控制語句:For,Do-While, While語句。
補充: Array對象有個Length屬性。
代碼片段一:
var items = [1, 2, 3, 3];
for(var index=0 ; index < items.Length; ++index) {
console.log(items[index]);
}
Note:雖然可以使用do-While 和While語句也可以,但常使用for語句。
方式二: 使用 for—in
補充:Array也是對象,for-in可以周遊對象,是以也可以周遊數組。
代碼片段二:
var items = [1, 2, 3, 3];
for(var index in items) {
console.log(items[index]);
}
Note:for-in周遊對象時無序的,是以不建議使用這種方式除非你确定這個無序的通路方式對你的代碼不會帶來任何不利影響。
方式三: 使用forEach方法
補充:Javascript 1.6中增加了給Array增加了一個新的成員方法forEach,可用來周遊數組。
代碼片段三:
var items = [1, 2, 3, 3];
items.forEach(function(item) {
console.log(item);
});
Output:1233
Note: forEach方法接受個回調函數作為參數,回調函數的參數完整格式callback(item, index, array); 參數1表示目前數組元素,參數2表示目前數組元素下标,參數3表示數組本身。
當然還有其他方式,這裡隻是列出了我常常使用的方式。。。歡迎吐槽