# 二、方法

### 一）、es5的方法

#### 1、for循环 (遍历出值)

let arr = ["terry","larry","tom","jacky"];
for(var i=0;i<arr.length;i++){
console.log(arr[i]);
}
//terry
//larry
//tom
//jacky


#### 2、while循环(遍历出值)

var arr = ["terry","larry","tom","jacky"];
var re = 0;
while(re<arr.length){
console.log(arr[re]);
re++;
}
//terry
//larry
//tom
//jacky


#### 3、do while循环(遍历出值)

var arr = ["terry","larry","tom","jacky"];
var re = 0;
do{
console.log(arr[re]);
re++;
}
while(re<arr.length)
//terry
//larry
//tom
//jacky


#### 4、for in 循环(遍历出值)

var arr = ["terry","larry","tom","jacky"];
for(var key in arr){
console.log(arr[key]);
}
//terry
//larry
//tom
//jacky

let arr = ["terry","larry","tom","jacky"];
for (let item in arr){
console.log("索引：",item);
}
//0
//1
//2
//3


### 二）、es6的方法

#### 5、for of 循环 (遍历出值)

for of 主要去遍历迭代器，

let arr = ["terry","larry","tom","jacky"];
for (let item of arr){
console.log("数组值：",item);
}
//terry
//larry
//tom
//jacky


#### 6、Array.prototype.keys方法（遍历出索引）

let arr = [1,3,4,6,8];
let a = arr.keys();
console.log(a);   //Object [Array Iterator] {}
//每次用迭代器去执行这个.next()方法，就会返回一个对象，对象的value属性值为数组的索引
a.next();         //{ value: 0, done: false }
a.next();		  //{ value: 1, done: false }
a.next();         //{ value: 2, done: false }
a.next();         //{ value: 3, done: false }
a.next();         //{ value: 4, done: false }
//迭代器遍历完，返回对象的done属性值为true
a.next();         //{ value: undefined, done: true }


let arr = ["terry","larry","tom","jacky"];
//获取迭代器
let values_iterator = arr.keys();
//通过迭代器获取数组中的元素
while(!(item = values_iterator.next()).done){//这里的done是执行迭代器.next后的返回值为对象的属性名
console.log(item.value);
}
//0
//1
//2
//3


let arr = ["terry","larry","tom","jacky"];
let entry_iterator = arr.keys();
for (let entry of entry_iterator){
console.log("索引",entry);
}
//0
//1
//2
//3


#### 7、Array.prototype.values方法(遍历出值)

let arr = ["terry","larry","tom","jacky"];
//获取迭代器
let values_iterator = arr.values();
//通过迭代器获取数组中的元素
while(!(item = values_iterator.next()).done){
console.log(item.value);
}
//terry
//larry
//tom
//jacky


let arr = ["terry","larry","tom","jacky"];
let entry_iterator = arr.values();
for (let entry of entry_iterator){
console.log("数组值",entry);
}
//terry
//larry
//tom
//jacky


#### 8、Array.prototype.entries方法（遍历出键值对）

while 遍历

let arr = ["terry","larry","tom","jacky"];
//获取迭代器
let values_iterator = arr.entries();
//通过迭代器获取数组中的元素
while(!(item = values_iterator.next()).done){
console.log(item.value);
}
//[ 0, 'terry' ]
//[ 1, 'larry' ]
//[ 2, 'tom' ]
//[ 3, 'jacky' ]


for of 遍历

let arr = ["terry","larry","tom","jacky"];
let entry_iterator = arr.entries();
for (let entry of entry_iterator){
console.log("数组键对",entry);
}
//[ 0, 'terry' ]
//[ 1, 'larry' ]
//[ 2, 'tom' ]
//[ 3, 'jacky' ]

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

火星人有可乐

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-25
08-17 129

03-13 1062
10-25 500
10-26 29
01-02
11-28 297