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(不能用于对象)