JavaScript中的循环总结

for () {}
效率最高
let a = [1, 2, 3, 4, 45, 44, 65, 65, ]

for (let i = 0; i < a.length; i++) {
	console.log(a[i])
}


forEach() 方法正在操作的数组
callback 为数组中每个元素执行的函数, 该函数接收一至三个参数:
currentValue 数组中正在处理的当前元素。
index 可选 数组中正在处理的当前元素的索引。
array 可选
thisArg 可选 可选参数。 当执行回调函数 callback 时, 用作 this 的值。

arr.forEach(callback(currentValue[, index[, array]])[, thisArg])
let a = [1, 2, 3, 4, 45, 44, 65, 65, ]

a.forEach((e, el, li) => {
	console.log(e, el, li)
})

不过需要注意的是你无法摆脱这个循环。


do ...
	while

let a = [1, 2, 3]
let i = 0;
do {
	console.log(a)
	i++

} while (i < a.length);
你可以使用continue跳转到下一个迭代:
您可以使用break中断while循环:

while

注意 条件为真的时候进, 会一直循环, 必须要有跳出循环条件 否则为死循环
可以使用continue跳转到下一个迭代: break中断while循环:
let a = [1, 2, 3, 4],
	v = true
while (a.length < 5 && v === true) {

	console.log(a)
	break

}


for... in 迭代对象的所有可枚举属性, 给出属性名称。 对象 {}
对象 {}
对象 {}
对象 {}
不是数组[]

let obj = {
	name: '历史',
	age: 19,
	sex: 'nan',
	jobo: 'js'
}

for (let key in obj) {
	//obj 为当前循环的对象
	//key 为对象的key 值
	console.log(obj[key])
}

for... of

a = ['a', 'b', 'c', 1, 2, 3, 54, 54, 98]
for (const va of a) {
	console.log(va) //数组的每一个值
}

// entries() 方法返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)
for (const [va, k] of a.entries()) {
	console.log(va, k) // key value
}

for... in vs
for... of

for... in 用它来便利对象
for... of 数组

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值