【js学习】for...in 与 for...of 区别

44 阅读1分钟
var arr = [1,2,3];//new String('123');
//打印对象属性值,数组或字符都是下标值
for (let index in arr) {
console.log('for in',typeof index,index);//string
}
// 打印数组的值
for (let index of arr) {
console.log('for of',typeof index,index);//number
}
// 打印数组的值
arr.forEach(index => {
console.log('forEach',typeof index,index);
});

// 对象属性值 与 值
var myObject={
  a:1,
  b:2,
  c:3
}
for (var key of Object.keys(myObject)) {
console.log('Object.keys',"key" + ":" + (typeof key) ,key);//number
console.log('Object.keys',"value" + ":" + (typeof myObject[key] , myObject[key]) );//
}