


The difference between for and for in in javascript, and why for in is not recommended
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]) }
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() }
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); };
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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.

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).

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 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.

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.

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.
