for…in访问的是key
for…of访问的是value
for...of
语句在可迭代对象(包括Array
,Map
,Set
,String
,TypedArray
,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
forEach通过回调函数,可以同时接收key和value两个变量
- forEach() 方法对数组的每个元素执行一次给定的函数。
- 只能用于数组的方法,其他类数组对象需要用Array.from()等方法转化为数组后再使用。
function forIn(elem){
for(let i in elem){
console.log(i)
}
}
function forOf(elem){
for(let i of elem){
console.log(i);
}
}
function each(elem){
elem.forEach((key,value) => {
console.log(key + '----' + value);
});
}
let arr = ['a','b','c']
let str = 'abc'
let obj = {
'a': 1,
'b': 2,
'c': 3
}
forIn(arr);//0 1 2
forOf(arr);//a b c
each(arr);// a----0 b----1 c----2
forIn(str); //0 1 2
forOf(str); // a b c
each(str); //报错,没有这个函数 is not a function
forIn(obj); //a b c
forOf(obj); // 报错 不是迭代器 is not iterable
each(obj); //报错,没有这个函数 is not a function
- for…in可以对所有对象使用
- for…of只能对可迭代对象使用
- forEach()只能对数组使用