循环事件(forEach、for…in和for…of)
有一次突然发现在forEach中,如果用return是无法退出整个循环,也拿不到返回值,但似乎可以跳出当前循环。
var arr = [1,1,2,1,1]
function test(){
arr.forEach((item)=>{
if(item==2)return item;
console.log("this is",item)
})
}
//test()
console.log(test())//output:undefined
按照MDN的说法
除了抛出异常以外,没有办法中止或跳出
forEach()
循环。如果你需要中止或跳出循环,forEach()
方法不是应当使用的工具。
function test(){
try{
arr.forEach((item)=>{
if(item==2)throw new Error("Error");//抛出错误,终止循环
console.log("this is",item)
})
}catch(error){
alert(error)
}
}
//test()
console.log(test())
零
这也让我想到了另外两个循环的方法->for…in和for…of
一
for…in主要是用来遍历对象属性的,因此如果你需要遍历例如数组的值,使用for…in反而不是恰当的选择。
var arr = [1,1,2,1,1]
for(let item in arr){
//if(item==2)return item;
console.log("this is",item)
}
output:
this is 0
this is 1
this is 2
this is 3
this is 4//这是在遍历数组的索引
当我们再给它增加新的属性
var arr = [1,1,2,1,1];
var reducer = (accumulator,currentValue)=>accumulator+currentValue;
//添加属性形式一👇
Object.defineProperty(arr,"sum",{
value:arr.reduce(reducer)
})
//添加属性形式二👇
arr.test = "first"
//添加属性形式三👇
Array.prototype.rank = "second"
console.log(Object.propertyIsEnumerable("sum"),Object.propertyIsEnumerable("first"),Object.propertyIsEnumerable("second"))
//console.log(arr)
for(let item in arr){
console.log("this is",item)
}
output:
false true false
this is 0
this is 1
this is 2
this is 3
this is 4
this is rank
this is test
这里有几点需要注意:
1.for…in只能够遍历出可枚举的属性
2.添加属性一的方法允许精确地添加或修改对象属性,其中定义的enumerable值默认为false,当该值修改为true时,可在遍历对象属性时显示出来。
3.添加属性二的方法是直接赋值属性,一般情况下可枚举
4.添加属性三的方法是直接在对象原型上添加属性,这种通过原型链继承的属性是可以在for…in被遍历出来的
Object.propertyIsEnumerable()可以确定对象中指定的属性是否可以被
for...in
循环枚举,但是通过原型链继承的属性除外。如果对象没有指定的属性,则此方法返回false
。
所以在打印是否可枚举的判断时,rank属性不被上述方法认可,返回false值
二
至于for…of,显而易见的,它与for…in不同的是,它可以用来纯粹的遍历数组的值。但除此之外,它也可以用来遍历类数组。像nodelist、HTMLCollection、arguments等都可以被看作是类数组。他们虽然有数组的length属性,可以被遍历,但不具有array其他的方法。这也就意味着用forEach遍历是不可取的,我们可以考虑采用直接for循环或者for…of来解决类数组遍历的问题。
<button class="wu">kanwo</button>
<button class="wu">kanwo</button>
<button class="you">kanwo</button>
<button class="wu">kanwo</button>
var col = document.getElementsByClassName("wu");
for(let item of col){
console.log("this is",item)
}