Home Web Front-end JS Tutorial How to use JavaScript for loop in multiple browsers_javascript skills

How to use JavaScript for loop in multiple browsers_javascript skills

May 16, 2016 pm 05:48 PM
for loop Browser

1. Foreword
The JavaScript language has slight differences in different browsers, but it is not as big as the difference in DOM operations. Now I will list one of the differences in "for loop" for you. And introduce how to effectively resolve this difference.

2. Problem Description
In the following test code example 1, the output results of IE6 and Chrome are inconsistent. IE6 does not execute the code in the for statement
Copy code The code is as follows:

//Example 1:
alert("Prepare to test whether toString is in a for loop Enumerated out")
var forTest = { toString: 1 }
for (i in forTest) {
alert("toString is looped out")//This is not executed under IE6, but Execute in Chrome and output the result value "1"
}

3. Analysis problem
Objects in JavaScript contain 'toString', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'hasOwnProperty', 'constructor' are seven built-in methods. These seven built-in methods cannot be enumerated using the for statement. But IE6 and Chrome have inconsistent support for built-in method overrides.
IE6: Although its built-in override method can be used, the FOR loop cannot be enumerated.
Chrome: You can override its built-in methods, and the FOR loop can also enumerate the overridden built-in methods.
So the output results of IE6 and Chrome browsers in the above test code example 1 are inconsistent

4. Solve the problem
To solve the problem described above, we need to do two things Things:
Whether the browser used by the user supports FOR loops to enumerate overridden built-in methods
How to elegantly solve the incompatibility problem so that all browsers can FOR loops to enumerate overridden built-in methods
(Solution code example 2)
Copy code The code is as follows:

//Example 2 :
enumerables = true,
forTest = { toString: 1 }
for (i in forTest) {
enumerables = null;
}
if (enumerables) {//These They are all properties of the Object object. The for loop of some browsers (ie6) will not traverse these properties, so you have to manually traverse the properties
enumerables = ['hasOwnProperty', 'valueOf', ' isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'constructor'];
}

//If enumerables is null, the browser supports the built-in method of enumeration override, Otherwise, you can only force the built-in method to be copied to the new object as shown in the following code.
/**
* Copy all attributes to the specified object
* @param {Object} object object to be merged
* @param {Object} config source attribute
* @return {Object} return the merged Object
*/
function apply(object, config) {
if (object && config && typeof config === 'object') {
var i, j, k ;
//The normal method of copying objects here
for (i in config) {
object[i] = config[i];
}
//Compatible with multiple browsers Built-in properties can be copied into new objects
if (enumerables) {
for (j = enumerables.length; j--;) {
k = enumerables[j];
if (config.hasOwnProperty(k)) {//Determine whether the object has a specific attribute. This property must be specified as a string. (For example, config.hasOwnProperty("toString"))
object[k] = config[k];
}
}
}
}
return object;
};

Now write some test codes to verify our results (test code example 3)
Copy the code The code is as follows:

//Example 3:
var a={};
for (i in forTest) {
a[i] = forTest[ i];
}
alert(a.toString) //If the copy fails under ie6, you can only enter "native code", not the value we overwrote.
var b=apply({},forTest)
alert(b.toString)//Using the apply function, the values ​​output in IE6 and Chrome are the coverage value we expect "1"

5. Summary
The author guesses that the for statement in IE6 marks those 7 built-in functions into the ignore list, so they cannot be enumerated in for no matter how they are overwritten, and Chrome can intelligently copy the overwritten built-in functions.
Use the apply function in Solution Code Example 2 to solve the problem of for loop inconsistency in multiple browsers.
The author is a rookie and rarely writes blogs. If I express my views incorrectly or make clerical errors, please be willing to ask the experts to correct them.

6. Frequently Asked Questions
Q: Why not first determine whether the browser version is IE6, and then set the corresponding enumeration scheme?
A: My personal point of view is that I am not sure there are so many browsers in the market (there are N browsers for PCs, as well as mobile browsers, and I don’t know what new versions of browsers will be available in the future). What mechanism is used for the for statement? So let’s test the mechanism of the for statement first.
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)

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Tips for using HDFS file system on CentOS Tips for using HDFS file system on CentOS Apr 14, 2025 pm 07:30 PM

The Installation, Configuration and Optimization Guide for HDFS File System under CentOS System This article will guide you how to install, configure and optimize Hadoop Distributed File System (HDFS) on CentOS System. HDFS installation and configuration Java environment installation: First, make sure that the appropriate Java environment is installed. Edit /etc/profile file, add the following, and replace /usr/lib/java-1.8.0/jdk1.8.0_144 with your actual Java installation path: exportJAVA_HOME=/usr/lib/java-1.8.0/jdk1.8.0_144exportPATH=$J

How to optimize website performance: Experiences and lessons learned from using the Minify library How to optimize website performance: Experiences and lessons learned from using the Minify library Apr 17, 2025 pm 11:18 PM

In the process of developing a website, improving page loading has always been one of my top priorities. Once, I tried using the Miniify library to compress and merge CSS and JavaScript files in order to improve the performance of the website. However, I encountered many problems and challenges during use, which eventually made me realize that Miniify may no longer be the best choice. Below I will share my experience and how to install and use Minify through Composer.

How to monitor HDFS status on CentOS How to monitor HDFS status on CentOS Apr 14, 2025 pm 07:33 PM

There are many ways to monitor the status of HDFS (Hadoop Distributed File System) on CentOS systems. This article will introduce several commonly used methods to help you choose the most suitable solution. 1. Use Hadoop’s own WebUI, Hadoop’s own Web interface to provide cluster status monitoring function. Steps: Make sure the Hadoop cluster is up and running. Access the WebUI: Enter http://:50070 (Hadoop2.x) or http://:9870 (Hadoop3.x) in your browser. The default username and password are usually hdfs/hdfs. 2. Command line tool monitoring Hadoop provides a series of command line tools to facilitate monitoring

How to solve the error in CentOS HDFS configuration How to solve the error in CentOS HDFS configuration Apr 14, 2025 pm 07:06 PM

Troubleshooting HDFS configuration errors under CentOS Systems This article is intended to help you solve problems encountered when configuring HDFS in CentOS systems. Please follow the following steps to troubleshoot: Java environment verification: Confirm that the JAVA_HOME environment variable is set correctly. Add the following in the /etc/profile or ~/.bashrc file: exportJAVA_HOME=/path/to/your/javaexportPATH=$JAVA_HOME/bin: $PATHExecute source/etc/profile or source~/.bashrc to make the configuration take effect. Hadoop

Use Composer to solve browser sniffing: The practical application of WhichBrowser/Parser library Use Composer to solve browser sniffing: The practical application of WhichBrowser/Parser library Apr 17, 2025 pm 11:21 PM

I encountered a tricky problem when developing a multi-device-compatible website: how to accurately identify the user's browser and device information. After trying multiple methods, I found that directly parsing user-agent strings (User-Agent) are both complex and unreliable, and often misjudgments occur. Fortunately, I successfully solved this problem by installing the WhichBrowser/Parser library using Composer.

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

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