【day4】for of和for in的区别

104 阅读1分钟
for in是es5的规范,可以理解为遍历键名
for of是es6新增的规范,可以理解为遍历键值

1、遍历数组   array = ['apple','pear','red']

for in,遍历得到array的键名 => 0,1,2

for of,遍历得到array的键值=>'apple','pear','red'

2、遍历对象 object = {name:'zs',age:'20',city:'guangzhou'}

for in,遍历得到object的键名=>'name','age','city'

for of,需要搭配

  • Object.key(object)=>遍历得到键名=>'name','age','city'
  • Object.values(object)=>遍历得到键值=>'name','age','city'
  • Object.entries(object)=>遍历得到键值对=>['name':'zs'],['age':'20'],['city:'guangzhou']