Table of Contents
for…in and for… The difference of " >for…in and for… The difference of
Extension" >Extension
Home Web Front-end JS Tutorial What is the difference between for…in and for…of in JS

What is the difference between for…in and for…of in JS

Dec 23, 2020 am 10:48 AM
javascript

This article will introduce to you the difference between for...in and for...of in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

What is the difference between for…in and for…of in JS

Related recommendations: "javascript video tutorial"

for…in and for… The difference of

#1. Traversing an array usually uses a for loop

If you have ES5, you can also use forEach, ES5 has Array traversal functions include map, filter, some, every, reduce, reduceRight, etc., but their return results are different. But if you use foreach to traverse the array, you cannot interrupt the loop using break, and you cannot return to the outer function using return.

Array.prototype.method=function(){
  console.log(this.length);
}
var myArray=[1,2,4,5,6,7]
myArray.name="数组"
for (var index in myArray) {
  console.log(myArray[index]);
}
Copy after login

2. Problems with for in traversing arrays

1.index is a string number and cannot be directly used for geometric operations

2. The traversal order may not be according to the internal order of the actual array

3. Using for in will traverse all enumerable properties of the array, including the prototype. For example, Shangli's prototype method method and name attribute are

, so for in is more suitable for traversing objects. Do not use for in to traverse arrays.

In addition to using a for loop, how can we traverse the array more simply and correctly to achieve our expectations (that is, without traversing method and name), the for of in ES6 is even better.

Array.prototype.method=function(){
  console.log(this.length);
}
var myArray=[1,2,4,5,6,7]
myArray.name="数组";
for (var value of myArray) {
  console.log(value);
}
Copy after login

Remember, for in traverses the index (i.e. key name) of the array, while for of traverses the array element values.

for of only traverses the elements in the array, not including the prototype attribute method and index name of the array

##3, Traversing objects

Traversing objects usually uses for in to traverse the key names of objects

Object.prototype.method=function(){
  console.log(this);
}
var myObject={
  a:1,
  b:2,
  c:3
}
for (var key in myObject) {
  console.log(key);
}
Copy after login

for in can traverse to the prototype method method of myObject. If you don’t want to traverse the prototype method and For attributes, you can judge it inside the loop. The

hasOwnPropery method can determine whether a property is an instance property of the object.

for (var key in myObject) {
  if(myObject.hasOwnProperty(key)){
    console.log(key);
  }
}
Copy after login

It can also be done through ES5's Object.keys(myObject) Gets an array of instance properties of an object, excluding prototype methods and properties

Object.prototype.method=function(){
  console.log(this);
}
var myObject={
  a:1,
  b:2,
  c:3
}
Copy after login

Summary

  • for..of is suitable for traversing collections with iterator objects such as numbers/array objects/strings/map/set. However, it cannot traverse objects because there is no iterator object. Unlike forEach(), it can correctly respond to break, continue and return statements

  • The for-of loop does not support ordinary objects, but if you want to iterate the properties of an object, you can use a for-in loop (which is its job) Or the built-in Object.keys() method:

  • for (var key of Object.keys(someObject)) {
      console.log(key + ": " + someObject[key]);
    }
    Copy after login
  • It is suitable to use destructuring when traversing the map object, for example;


  • for (var [key, value] of phoneBookMap) {
       console.log(key + "'s phone number is: " + value);
    }
    Copy after login
  • When you add the myObject.toString() method to an object, you can convert the object into a string. Similarly, when you add the myObjectSymbol.iterator method to any object, you can Traverse this object.

    For example, suppose you are using jQuery. Although you are very fond of the .each() method inside, you still want the jQuery object to also support for-of loops. You can do this:

  • jQuery.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    Copy after login
All objects that have Symbol.iterator are called iterable. In the following articles, you will find that the concept of iterable objects is used almost throughout the entire language, not only the for-of loop, but also the Map and Set constructors, destructuring assignment, and the new spread operator.

  • Steps of for...of

    The or-of loop first calls the Symbol.iterator method of the collection, and then returns a new iterator object. The iterator object can be any object with a .next() method; the for-of loop will call this method repeatedly, once for each loop. For example, this code is the simplest iterator I can come up with:

  • var zeroesForeverIterator = {
     [Symbol.iterator]: function () {
       return this;
      },
      next: function () {
      return {done: false, value: 0};
     }
    };
    Copy after login

Extension

JS array traversal:

1. Ordinary for loop

var arr = [1,2,0,3,9];
 for ( var i = 0; i <arr.length; i++){
    console.log(arr[i]);
}
Copy after login

2. Optimization Version of the for loop

Use variables to cache the length to avoid repeated acquisition of the length. When the array is large, the optimization effect is obvious

for(var j = 0,len = arr.length; j < len; j++){
    console.log(arr[j]);
}
Copy after login

3.forEach

Introduced by ES5, the loop that comes with the array has its main function of traversing the array. Its actual performance is weaker than for.

arr.forEach(function(value,i){
  console.log(&#39;forEach遍历:&#39;+i+&#39;--&#39;+value);
})
Copy after login

forEach method also has a small flaw: you cannot use the break statement. To interrupt the loop, you cannot use the return statement to return to the outer function.

4.map traversal

map means "mapping" and its usage is similar to forEach. Likewise,

the break statement cannot be used to interrupt the loop. Nor can you use the return statement to return to the outer function.

arr.map(function(value,index){
    console.log(&#39;map遍历:&#39;+index+&#39;--&#39;+value);
});
Copy after login

Map traversal supports the use of return statements and return values

var temp=arr.map(function(val,index){
  console.log(val);  
  return val*val           
})
console.log(temp);
Copy after login

forEach、map都是ECMA5新增数组的方法,所以ie9以下的浏览器还不支持

5.for-of遍历

ES6新增功能

for( let i of arr){
    console.log(i);
}
Copy after login
  • for-of这个方法避开了for-in循环的所有缺陷

  • 与forEach()不同的是,它可以正确响应break、continue和return语句

for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM NodeList对象。for-of循环也支持字符串遍历

JS对象遍历:

1.for-in遍历

for-in是为遍历对象而设计的,不适用于遍历数组。(遍历数组的缺点:数组的下标index值是数字,for-in遍历的index值"0","1","2"等是字符串)

for-in循环存在缺陷:循环会遍历对象自身的和继承的可枚举属性(不含Symbol属性)

for (var index in arr){
    console.log(arr[index]);
    console.log(index);
}
Copy after login

2.使用Object.keys()遍历

返回一个数组,包括对象自身的(不含继承的)所有可枚举属性(不含Symbol属性).

var obj = {&#39;0&#39;:&#39;a&#39;,&#39;1&#39;:&#39;b&#39;,&#39;2&#39;:&#39;c&#39;};
Object.keys(obj).forEach(function(key){
     console.log(key,obj[key]);
});
Copy after login

3.使用Object.getOwnPropertyNames(obj)遍历

返回一个数组,包含对象自身的所有属性(不含Symbol属性,但是包括不可枚举属性).

var obj = {&#39;0&#39;:&#39;a&#39;,&#39;1&#39;:&#39;b&#39;,&#39;2&#39;:&#39;c&#39;};
Object.getOwnPropertyNames(obj).forEach(function(key){
    console.log(key,obj[key]);
});
Copy after login

4.使用Reflect.ownKeys(obj)遍历

返回一个数组,包含对象自身的所有属性,不管属性名是Symbol或字符串,也不管是否可枚举.

var obj = {&#39;0&#39;:&#39;a&#39;,&#39;1&#39;:&#39;b&#39;,&#39;2&#39;:&#39;c&#39;};
Reflect.ownKeys(obj).forEach(function(key){
  console.log(key,obj[key]);
});
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of What is the difference between for…in and for…of in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles