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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1251
24
How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

Why is the rise or fall of virtual currency prices? Why is the rise or fall of virtual currency prices? Why is the rise or fall of virtual currency prices? Why is the rise or fall of virtual currency prices? Apr 21, 2025 am 08:57 AM

Factors of rising virtual currency prices include: 1. Increased market demand, 2. Decreased supply, 3. Stimulated positive news, 4. Optimistic market sentiment, 5. Macroeconomic environment; Decline factors include: 1. Decreased market demand, 2. Increased supply, 3. Strike of negative news, 4. Pessimistic market sentiment, 5. Macroeconomic environment.

Why does the Spring project cause randomness problems due to circular dependencies when starting? Why does the Spring project cause randomness problems due to circular dependencies when starting? Apr 19, 2025 pm 11:21 PM

Understand the randomness of circular dependencies in Spring project startup. When developing Spring project, you may encounter randomness caused by circular dependencies at project startup...

Why is the return value empty when using RedisTemplate for batch query? Why is the return value empty when using RedisTemplate for batch query? Apr 19, 2025 pm 10:15 PM

Why is the return value empty when using RedisTemplate for batch query? When using RedisTemplate for batch query operations, you may encounter the returned results...

Why does the redisTemplate.opsForList().leftPop() method not support passing in parameters to pop up multiple values ​​at once? Why does the redisTemplate.opsForList().leftPop() method not support passing in parameters to pop up multiple values ​​at once? Apr 19, 2025 pm 10:27 PM

Regarding the reason why RedisTemplate.opsForList().leftPop() does not support passing numbers. When using Redis, many developers will encounter a problem: Why redisTempl...

What is the difference between php framework laravel and yii What is the difference between php framework laravel and yii Apr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

Why can't JavaScript directly obtain hardware information on the user's computer? Why can't JavaScript directly obtain hardware information on the user's computer? Apr 19, 2025 pm 08:15 PM

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

See all articles