w3pop.com :: ÍøÂçѧԺ :: JavaScript :: JS ±äÁ¿
A variable is a "container" for information you want to store.
±äÁ¿ÊÇÄãÏëÒª´æ´¢ÐÅÏ¢µÄ“ÈÝÆ÷”
Variable[±äÁ¿]
Variables are used to store data. This example will show you how.
Õâ¸öÀý×Ó½«¸øÄãչʾÔõÑùÀ´´æ´¢Êý¾Ý
A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value.
±äÁ¿ÊÇÄãÏëÒª´æ´¢Êý¾ÝµÄ“ÈÝÆ÷”¡£±äÁ¿µÄÖµ¿ÉÒÔÔڽű¾Öиı䡣Äã¿ÉÒÔµ÷ÓñäÁ¿µÄÃû³ÆÀ´¿´¿´ËüµÄÖµ»òÊǸıäËüµÄÖµ
Rules for variable names:
±äÁ¿Ãû³Æ¹æÔò£º
IMPORTANT! JavaScript is case-sensitive! A variable named strname is not the same as a variable named STRNAME!
ÖØµã×¢Ò⣡JSÊÇÇø·Ö´óСдµÄ£¡Ò»¸öÃû³ÆÎªstrnameµÄ±äÁ¿ºÍÃûΪSTRNAMEµÄ±äÁ¿ÊDz»Í¬µÄ
You can create a variable with the var statement:
Äã¿ÉÒÔͨ¹ý"var"Óï¾ä½¨Á¢Ò»¸ö±äÁ¿£º
var strname = some value |
You can also create a variable without the var statement:
ÄãÒ²¿ÉÒÔ²»ÓÃvarÀ´½¨Á¢±äÁ¿£º
strname = some value |
You can assign a value to a variable like this:
¿ÉÒÔÓÃÕâÑùµÄ·½·¨À´¸ø±äÁ¿Ö¸¶¨Öµ£º
var strname = "Hege" |
Or like this:
»òÕßÕâÑù£º
strname = "Hege" |
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "strname" has the value "Hege".
±äÁ¿Ãû³ÆÐ´ÔÚ±í´ïʽµÄ×ó±ß£¬ÄãÏëÒªÖ¸¶¨µÄֵдÔÚÓұߡ£ÏÖÔÚ±äÁ¿Ãû³ÆÎª"strname"µÄ±äÁ¿ÖµÎª"Hege"¡£
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.
µ±ÄãÔÚfunction(º¯Êý)ÀïÖ¸¶¨Ò»¸ö±äÁ¿£¬Ëü¾ÍÖ»ÄÜÔڸú¯ÊýÄÚ½øÐзÃÎÊ¡£µ±ÄãÀ뿪º¯Êý±äÁ¿¾ÍÎÞЧÁË¡£ÕâÑùµÄ±äÁ¿¿ÉÒÔ³Æ×÷¾Ö²¿±äÁ¿¡£Äã¿ÉÒÔÔÚ²»Í¬µÄº¯ÊýÄÚʹÓÃͬÑùÃû³ÆµÄ±äÁ¿£¬ÒòΪÔÚº¯ÊýÖÐÖ»»á±æÈÏËüËùÖ¸¶¨µÄ±äÁ¿£¨±ðµÄº¯ÊýÔõô¶¨ÒåÊDz»¹ÜµÄ£©
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
Èç¹ûÄãÔÚº¯ÊýÍⶨÒåÒ»¸ö±äÁ¿£¬ÄÇÒ³ÃæÀïËùÓеĺ¯Êý¶¼¿ÉÒÔ·ÃÎÊËü¡£ËüµÄÓÐЧ·¶Î§´ÓÖ¸¶¨¿ªÊ¼Ö±µ½Äã¹Ø±ÕÒ³Ãæ²Å»á½áÊø¡£