zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

JavaScript for of &# with 39 Over loop
2023-09-14 09:00:51 时间

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.