Home Web Front-end JS Tutorial js for loop, why must you add var to define i variable_javascript skills

js for loop, why must you add var to define i variable_javascript skills

May 16, 2016 pm 06:24 PM
for loop js

For example, below.

Copy code The code is as follows:

for(i=0;i<10;i ) {//Do not write it as: var i=0
 alert(i);
}

 However, this is really not a good habit. Let me talk about why I write Js Be sure to add var to the for loop, otherwise it will bring you annoying and difficult-to-find bugs from time to time.
For example, now we want to implement the following function: output
10
20
30
40
50
60
70
80
90
 100
 Through the following code, WriteNumber loops from 1 to 10, and each loop calls the TenTimes method to return 10 times the index value.
Copy code The code is as follows:



You will find that only 10 is output in the end. You can run the test using the code box below.

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]
关于在WriteNumber和TenTimes方法里加不加var,就是说是否声明索引变量i有4种情况:
  第一种情况,WriteNumber和TenTimes各有1个for循环,2个循环里均没有用var声明i索引变量。
  运行结果:会alert出1。结果只输出了10,不是我们所想要的。
  分析:执行WriteNumber时,其作用域内并没有找到声明过的变量i,直接对i进行赋值,则隐式的将i声明为全局变量,(对于函数内部未声明过的变量,如果给它赋值,会隐式的将它声明为全局变量。) 循环开始,i=1,调TenTimes方法,发现TenTimes方法也没有声明过变量i ,所以TenTimes里的i就是全局变量i,就和WriteNumber的i成了同一个。 这时line9 alert出来的自然是1了。TenTimes循环了10次,使得全局的i变成了11,自然WriteNumber就不会执行第2次循环操作了。
  验证:如果在WriteNumber();语句后加alert(i),即取消line16的注释,会发现alert出12(12=10+2个i++),证明了i此时为windows对象。
  第二种情况,WriteNumber声明了i变量,即line3: var i=1,TenTimes未声明i变量,即line10: i=1。
  运行结果:line9 alert(i)处报i未定义错误 ,因为WriteNumber有声明过变量i,所以没有成为全局的i,TenTimes执行时又没有声明过i,所以报未定义。若注释掉line9,输出结果正确。因为当TenTimes里运行到i=1时,隐式将i声明是全局变量,不影响WriteNumber里的i。WriteNumber仍然会执行10次循环。
  验证:如果在WriteNumber();语句后加alert(i),即取消line16的注释,会发现alert出11(11=10+TenTimes里的i++),证明了此时有windows.i。
  第三种情况,WriteNumber没有声明i变量,即line3: i=1,TenTimes声明了i变量,即line10: var i=1。
  运行结果:弹出10个undefined。因为WriteNumber未声明i,隐式将i声明是全局变量,而TenTimes有声明过变量i(补充一句,对于变量的声明都是在预编译中进行的),所以line9 alert(i)里的i不是windows.i,而是TenTimes声明的变量i,此时当然是undefined了。同时,发现输出结果正确,因为TenTimes的i不会影响WriteNumber的全局i,WriteNumber仍然是执行了10次循环。
  第四种情况:WriteNumber和TenTimes均用var声明了i。
  运行结果:注释掉line9,不说了,好习惯,结果当然完美。
  虽然第二、三种情况输出结果是正确的,但是对i的使用很混乱,应该算是运气导致结果正确,因为刚好1个是window.i,一个是函数内部的私有变量i,使得没有冲突。
此文虽然讲的是写for循环为什么一定要加var,但其实讲的是变量的作用域(或者说变量的生命周期)。理解之后,下面的2段code运行结果你应该能准确说出答案吧。

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

Ps:说道coding的好习惯,想起了这个:if(a==3) 应该写成if(3==a) 。因为我们常会把==写成1个=,如果把变量写在右边时只写了1个=,就会报编译错误,这样就能及时发现错误。
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)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles