for in , for of 和forEach的区别
1、对象
- for in可以枚举对象,循环打印出来的是对象的key值
const myObject={
today:'在家学习',
tomorrow:'上班'
}
for (let todo in myObject){
console.log(todo)
}
//today
//tomorrow
- for of 不可以对对象进行循环,会报错,具有iterator接口的,才可以用for of 遍历它的成员,如果想循环对象,就必须在其 Symbol.iterator 的属性上部署遍历器生成方法(或者原型链上的对象具有该方法)
const myObject={
today:'在家学习',
tomorrow:'上班'
}
for (let todo of myObject){
console.log(todo)
}
//index.html:16 Uncaught TypeError: myObject is not iterable
- forEach 报错 不能对对象进行遍历
const myObject={
today:'在家学习',
tomorrow:'上班'
}
myObject.forEach(element => {
console.log(element)
});
//index.html:16 Uncaught TypeError: myObject.forEach is not a function
2、数组
for…of…是输出数组值
for…in…是输出索引值
const myArray=['沪上阿姨','茶百道','书亦烧仙草']
for (let teaWithMilk of myArray){
console.log(teaWithMilk)
}
//沪上阿姨 茶百道 书亦烧仙草
for (let teaWithMilk in myArray){
console.log(teaWithMilk)
}
//0 1 2
myArray.forEach(item=>{
console.log(item)
})
//沪上阿姨 茶百道 书亦烧仙草
3、原型对象
for of不会输出数组的原型对象。
const myArray=['沪上阿姨','茶百道','书亦烧仙草']
Array.prototype.paly=()=>{
console.log('羊了个羊第二关很难')
}
myArray.name='钟雨晴'
for (let teaWithMilk of myArray){
console.log(teaWithMilk)
}
//沪上阿姨
//茶百道
//书亦烧仙草
for in 不仅返回的是数组的下标,而且将数组的原型对象以及数组对象本身属性值都会返回。
const myArray=['沪上阿姨','茶百道','书亦烧仙草']
Array.prototype.paly=()=>{
console.log('羊了个羊第二关很难')
}
myArray.name='钟雨晴'
for (let teaWithMilk in myArray){
console.log(teaWithMilk)
}
//0
//1
//2
//name
//play
//但在实际工作开发中,这些对象很可能是不需要的,全部列举出来可能会产生新的问题。
//为了解决原型对象这个问题,可以使用hasOwnProperty
const myArray=['沪上阿姨','茶百道','书亦烧仙草']
Array.prototype.paly=()=>{
console.log('羊了个羊第二关很难')
}
myArray.name='钟雨晴'
for (let teaWithMilk in myArray){
if(myArray.hasOwnProperty(teaWithMilk)){
console.log(teaWithMilk)
}
}
//0
//1
//2
//name
//虽然使用hasOwnProperty,但是数组本身的属性还是会输出
使用forEach可以输出索引值和数组值,而且不会输出数组的原型对象。
const myArray=['沪上阿姨','茶百道','书亦烧仙草']
Array.prototype.paly=()=>{
console.log('羊了个羊第二关很难')
}
myArray.name='钟雨晴'
myArray.forEach((item,index)=>{
console.log(item,index)
})
//沪上阿姨 0
//茶百道 1
//书亦烧仙草 2
4是否可以break
forEach有个问题就是不能中断执行
const myArray=['5','6','7']
myArray.forEach(item=>{
console.log(item)
if(item==5){
return false;
}
})//5 6 7 从结果可以看出,return false没有执行
for of、for in 可以使用break
const myArray=['5','6','7']
for (let test in myArray){
console.log(test)
if(myArray[test]==5){
break;
}
}
//0
for (let test of myArray){
console.log(test)
if(test==5){
break;
}
}
//5