Home Web Front-end JS Tutorial The difference between for and for in in javascript, and why for in is not recommended

The difference between for and for in in javascript, and why for in is not recommended

Jul 17, 2017 pm 02:13 PM
javascript js Why

In

jsthere are two ways to traverse an array

var array=['a']
//标准的
for循环
for(var i=1;i<array.length;i++){
    alert(array[i])
}
//
foreach
循环
for(var i in array){
    alert(array[i])
}
Copy after login

Under normal circumstances the results of the above two ways of traversing an array are the same. First let’s talk about the first difference between the two

The i in the standard for loop is of type number, which represents the subscript of the array, but the i in the foreach loop represents that the key of the array is of type string. Because everything in js is object. Try it yourself alert(typeof i); This difference is a minor problem. Now that I add the following code, the above execution results will be different.

//扩展了js原生的Array
Array.prototype.test=function()
 
}
Copy after login

Try and see what the above code does. We found that the standard for loop still truly loops over the array, but at this time the foreach loop prints out the test method I just wrote. This is the biggest difference between for and foreach to traverse the array. If we use foreach to traverse the array in the project, suppose that one day someone accidentally extends the native Array class of js, or introduces an external js framework and also extends the native Array. . Then comes the problem.

Why not use for in statement?

Keywords: native Array class, extended Array class
The potential bug of using the for in statement to traverse array objects is: if the native Array class is modified by other js script libraries Prototype extension (for example, adding an additional toJSON method, namely Array.prototype.toJSON=xxxx), then the logic of using for in to traverse the expanded Array object will be different from the logic of traversing the native Array object.
To give a simple example,

var x=[1]; 
for(var s in x){ 
alert(s); 
};
Copy after login

According to common sense, if Array is a native js class, the above statement should only execute the alert method once, and s is the index 0 of the array. However, if the Array class is extended with an additional toJSON method, then the above statement will execute alert twice, the first time s is index 0, and the second time s is the method name 'toJSON'.

If the logic of the code you design is based on the native Array class, and one day your colleague references a third-party JS library on the page, and this library happens to extend the Array class, the result will be difficult Imagine that it is very likely that the original code logic will no longer hold.

Regarding this kind of library that extends native JS classes, a well-known one is prototype.js, which extends many methods to the Array class such as toJSON, each, etc. I now understand why the founder of jquery was so angry about prototype (many people use jquery and prototype on the same page for special reasons. There will be many unexpected conflict problems that cannot be solved by just a noConflict. ). In addition, if the author of jqModal understands my article, he will probably complain about the prototype and say: "It is unwise for me to use for in to traverse the array, but the worse thing is the prototype..."

As mentioned above, if you are using jqModal and also using prototype for other reasons, congratulations on your success. The conflict will cause jqModal's pop-up box to be unable to automatically close using the button set by closeClass under ie6 and ie7. Trace the debugging code and you will find that the exception is in the for in loop of the hs method mentioned at the beginning of this article. . .
3. Solve the problem
When traversing the array, use the for var statement instead of for in.

The above is the detailed content of The difference between for and for in in javascript, and why for in is not recommended. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

The relationship between Bootstrap Table garbled and page encoding The relationship between Bootstrap Table garbled and page encoding Apr 07, 2025 pm 12:03 PM

Bootstrap Table garbled is usually because the page encoding is inconsistent with the table data encoding. To solve this problem, you need to make sure they are consistent. The specific steps include: checking page and table data encoding, setting page encoding, and verifying the encoding. If UTF-8 is used, the server should also support it. If it cannot be resolved, try using the JavaScript encoding library.

Can JS run without H5? Can JS run without H5? Apr 06, 2025 am 09:06 AM

Is JavaScript available to run without HTML5? The JavaScript engine itself can run independently. Running JavaScript in a browser environment depends on HTML5 because it provides the standardized environment required to load and execute code. The APIs and features provided by HTML5 are crucial to modern JavaScript frameworks and libraries. Without HTML5 environments, many JavaScript features are difficult to implement or cannot be implemented.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

mysql cannot terminate the process mysql cannot terminate the process Apr 08, 2025 pm 02:48 PM

The kill command in MySQL sometimes fails because of the special process status and improper signal level. Methods to effectively terminate the MySQL process include: confirming the process status, using the mysqladmin command (recommended), using kill -9 with caution, checking system resources, and in-depth troubleshooting of error logs.

Centos stops maintenance 2024 Centos stops maintenance 2024 Apr 14, 2025 pm 08:39 PM

CentOS will be shut down in 2024 because its upstream distribution, RHEL 8, has been shut down. This shutdown will affect the CentOS 8 system, preventing it from continuing to receive updates. Users should plan for migration, and recommended options include CentOS Stream, AlmaLinux, and Rocky Linux to keep the system safe and stable.

How to backup and restore database after mysql installation How to backup and restore database after mysql installation Apr 08, 2025 am 11:45 AM

There is no absolutely optimal MySQL database backup and recovery solution, and it needs to be selected based on the amount of data, business importance, RTO and RPO. 1. Logical backup (mysqldump) is simple and easy to use, suitable for small databases, but slow and huge files; 2. Physical backup (xtrabackup) is fast, suitable for large databases, but is more complicated to use. The backup strategy needs to consider the backup frequency (RPO decision), backup method (data quantity and time requirement decision) and storage location (off-site storage is more secure), and regularly test the backup and recovery process to avoid backup file corruption, permission problems, insufficient storage space, network interruption and untested issues, and ensure data security.

Vue and Element-UI cascaded drop-down box remote search Vue and Element-UI cascaded drop-down box remote search Apr 07, 2025 pm 07:33 PM

The key to the efficient remote search cascading selection box is: a reasonable request strategy: load data on demand, avoid loading all data at once. Data processing: The data structure returned by the backend should be standardized, and error handling and loading status prompts should be done well. Performance optimization: Consider paging, caching and code optimization to improve loading efficiency.

See all articles