js循环遍历数组(对象)

js循环遍历数组(对象)

1,for循环

对于循环应该是最常用的一种遍历方式了,通常用来遍历数组结构。

let arr = ['a','b','c'];
for (let i=0; i<arr.length; i++){
	console.log(i,arr[i]);
}
//输出
//0 a
//1 b
//2 c

2,forEach循环

forEach方法用于调用数组的每个元素,并将元素传递给回调函数。对于空数组不会执行回调函数。

let arr = [1,2,3];
arr.forEach(function(i,index){
	console.log(i,index)
})
//输出
// 1 0
// 2 1
// 3 2

3,map方法

map返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

let arr = [1,2,3];
let newArr = arr.map(function(i){
	console.log(i) // 1 2 3 
	return i*2;
})
console.log(arr) //[1,2,3]
console.log(newArr) //[2,4,6] 

4,for…in循环

for…in语句用于对数组或者对象的属性进行循环操作。

for…in循环中的代码每执行一次,就会对数组或者对象的属性进行一次操作。

//遍历对象时,拿到的是键名,不能直接获取键值。
let obj={name:'programmer',age:'22',height:'180'};
for(let key in obj){
	console.log(key,obj[key])
}
//输出
//name programmer
//age 22
//height 180
//可以直接修改原对象
for(let key in obj){
	obj[key] = key
}
console.log(obj) //{name: "name", age: "age", height: "height"}
//遍历数组时,拿到的是下标
let arr = ['a','b','c'];
for (let index in arr){
	console.log(index,arr[index]);
}
//输出
//0 a
//1 b
//2 c
//可以直接修改原数组
for(let index in arr){
	arr[index] = index
}
console.log(arr)  // ["0", "1", "2"]

5,for…of循环

因为是es6引入到新特性中的,借鉴c ++,java,c#和python语言,引入for…of循环,作为遍历所有数据结构的统一方法。

var arr = ['a', 'b', 'c', 'd'];
for (let item of arr) {
	console.log(item); // a b c d
}
//在遍历JSON时,我自己跟喜欢用for...of,因为可以直接操作item
var arr = [{a:1,b:2},{a:3,b:4}];
for (let item of arr) {
	item.a = 999
}
console.log(arr) //[{a:999,b:2},{a:999,b:4}]

6,while循环

while用于循环作用基本一致,通常用来循环数组

let cars=["BMW","Volvo","Saab","Ford"];
let i=0;
while (cars[i]){    //()里面是判断条件
	console.log(cars[i]) // BMW Volvo Saab Ford
	i++;
};

7,do while循环

do while 是while的一个亲戚,它在循环开始前先执行一次操作,然后才进行判断,true就继续执行,false就结束循环。

let i = 3;
do{
	console.log(i) // 3 2 1
	i--;
}
while(i>0);

第一回创作,在学习的道路上,记录一下我学到的小知识,要是有错误,请各位及时指正,万分感谢,要是有所不足,也请指出,我也会继续添加。

遇到的难题,我也想学习到了,能总结、并且记录下来,好记性不如烂笔头,一只小菜鸟,以此篇开始记录我的成长之路

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值