js:常用的遍历方法记录一下

1、for循环可以遍历字符串和数组

let str = "我在测试";
for(let i = 0;i < str.length;i++){
    console.log(i,str[i]);
}
let arr = ['我','在','测','试'];
for(let j = 0;j < arr.length;j++){
      if(arr[j] == '我'){
      		break;//for循环时可以使用break跳出循环
      }		
    console.log(j,arr[j]);
}

2、forEach(数组遍历)

//forEach结合try...catch()可以跳出循环
try {
    var arr = [1, 2, 3, 4];
    arr.forEach(function (item, index) {
        //跳出条件
        if (item === 2) {
            throw new Error("LoopTerminates");
        }
        //do something
        console.log(item);
    });
} catch (e) {
    if (e.message !== "LoopTerminates") throw e;
};
//return 不会终止forEach循环,并返回值的作用
let arr = [1, 2, 3, 4];
function find(array, num) {
    array.forEach((self, index) => {
        if (self === num) {
            return index;
        };
        console.log(index);
    });
};
let index = find(arr, 2);
let arr = [1, 2, 3, 4];
function find(array, num) {
    array.forEach((self, index) => {
        console.log(index);
        if (self === num) {
            return index;
        };
    });
};
let index = find(arr, 2);// 这个和上面的一个,有点意思
//forEach通过函数,返回下标
let arr = [1, 2, 3, 4];
function find(array, num) {
    let _index = ''
;    array.forEach((self, index) => {
        if (self === num) {
            _index = index;
        };
    });
    return _index;
};
let index = find(arr, 2);
console.log(index);
//forEach删除自身元素index不会被重(超自他人)
arr.forEach((item, index) => {
    arr.splice(index, 1);//splice会改变数组的长度
    console.log(1);
    //这里隐性让index自增加1
    index++;
});
//可以通过扩展运算符修复上面的问题
//(通过拓展运算符重置数组arr,达到不跳出循环的目的,
//你会发现内部确实执行了两次,很遗憾的是index依旧没被重置,
//所以数组arr还是无法在遍历的同时删空自己。)
[...arr].forEach((item, index) => {
    arr.splice(index, 1);
    console.log(1);
});

3、for in(建议搭配对象,数组也是可以的)

//使用 break 或者 continue 去中断循环,不可以直接用 return 去中断循环
let obj = {
	name:'lms',
	sex:'girl',
	age:'18'
};
for(let item in obj){
	console.log(item);
	if(item == 'name'){
		break;
	}
}

4、for of(不能用于对象)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值