ES6遍历数组和对象遍历

使用JS对对象的少少体会

const arr = ['red', 'green', 'blue'];

arr.forEach(function (element, index) {
console.log(element); // red green blue
console.log(index); // 0 1 2
});

let arr = [3, 5, 7];
arr.foo = 'hello';

for (let i in arr) {
console.log(i); // "0", "1", "2", "foo"
}

for (let i of arr) {
console.log(i); // "3", "5", "7"
}
for...of循环不会返回数组arr的foo属性

对象遍历方法

获取键值
for (var key of Object.keys(someObject)) {
console.log(key + ': ' + someObject[key]);}

键名和键值
function* entries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}}

for (let [key, value] of entries(obj)) {
console.log(key, '->', value);}

返回键名数组
Object.keys(obj)

你可能感兴趣的:(ES6遍历数组和对象遍历)