[Javascript] Iterate Over Items with JavaScript's for-of Loop

In this lesson we will understand the For Of loop in Javascript which was introduced in ES6. The for-of loop lets you iterate of an itterable object (array, string, set, or map) and returns each objects value in a specified variable. This excludes plain objects as we will see in the lesson.

 

Object.prototype.objCustom = function() {}; 
Array.prototype.arrCustom = function() {};

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

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

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

for (let i of iterable) {
  console.log(i); // 3, 5, 7
}

 

"accCustom" and "objCustom" are not logged in second loop is because they are inherited. Not array and object's own prop.

 

posted @ 2017-09-14 01:05  Zhentiw  阅读(208)  评论(0编辑  收藏  举报