Přehled proměnných
Proměnnéareveryusefulbecausetheyallowyoutoassignashort,easy-to-remembernametoeverypieceofdatayouintendtouseintheprogram.Proměnnécansavethedataenteredbytheuserwhentheprogramisrunning(forexample,usetheInputBoxfunctiontodisplayadialogboxonthescreen,andthensavethetexttypedbytheuserintothevariable),theresultofaspecificoperation,andapieceofdatatobedisplayedontheform,etc..Inshort,variablesaresimpletoolsfortrackingalmostalltypesofinformation.
Ifthereisnoassignmentafterthevariabledeclaration,thecompilerwillautomaticallypromptandassignadefaultvalue.
Proměnnéareconvenientplaceholdersforreferencingcomputermemoryaddresses,whichcanstoreprograminformationthatcanbechangedwhileScriptisrunning.Forexample,youcancreateavariablenamedClickCounttostorethenumberoftimestheuserclicksanobjectontheWebpage.Tousevariables,youdonotneedtoknowtheaddressofthevariableinthecomputer'smemory.Youcanvieworchangethevalueofthevariableaslongasyourefertothevariablebyitsname.ThereisonlyonebasicdatatypeinVBScript,namelyVariant,sothedatatypeofallvariablesisVariant.
Pravidla pro pojmenování
Firstofall,wemustgivethevariableasuitablename,asifeveryonehastheirownname,otherwiseitwillbedifficulttodistinguish.InVB6,thenamingofvariablesmustfollowthefollowingrules:
(1)Variablenamesmuststartwithaletterorunderscore,andthemiddleofthenamecanonlyconsistofletters,numbersandanunderscore"_";thelastcharactercanbeItisatypespecifier;
(2)Thelengthofthevariablenamemustnotexceed255characters;
(3)Thevariablenamemustbeuniquewithinthevalidrange.Theeffectivescopeisthescopeofthereferencevariablethatcanberecognizedandusedbytheprogram—forexample,aprocedure,awindow,andsoon.Thecontentofthescopeofreferencevariableswillbeintroducedlater.
(4)Variablenamescannotbereservedwords(keywords)inVB,orreservedwordswithtypespecifiersattheend,butreservedwordscanbeembeddedinvariablenames,keywordsrefertoVB6Internalsystemidentifierssuchasattributes,events,methods,procedures,andfunctionsinthelanguage.Suchasdefinedwords(if,endif,while,loop,etc.),functionnames(len,format,msgbox,etc.).LikePrint,Print$isillegal,butMyprintislegal.Forexample:strName1,intMax_Length,intLesson,strNo3,etc.arelegalvariablenames,whileA&B,allright,3M,_Number,etc.areillegalvariablenames.
Poznámka:
(1)VariablenamesarenotcasesensitiveinVB(suchasABC,aBc,abc,etc.).Clanguageiscasesensitive.Differentlanguageshavedifferentrules.
(2)Whendefiningandusingvariables,usuallydefinethevariablenameasanamethatiseasytouseandreadandcandescribetheusefulnessofthecontaineddata,insteadofusingsomedifficultabbreviationssuchasAorB2.Forexample:Supposeyouarecompilingasoftwareforsellingapplesforthefruitshop.WeneedtwovariablestostorethepriceandsalesofApple.Atthispoint,youcandefinetwovariablesnamedApple_PriceandApple_Sold.Eachtimetheprogramisrun,theuserprovidesspecificvaluesforthesetwovariables,whichlooksveryintuitive.Thespecificmethodis:Makethemeaningofthevariableclearbyformingameaningfulvariablenamewithoneormorewords.Forexample,thevariablenameSalesTaxRateismuchclearerthanTaxorRate.
(3)Mixuppercaseandlowercaselettersandnumbersasneeded.Areasonableagreementistocapitalizethefirstletterofeachwordinthevariable,forexample:DateOfBirth.
(4)Anotherreasonableagreementisthateachvariablenamestartswithatwo-orthree-characterabbreviation,whichcorrespondstothedatatypeofthevariabletobestored.Forexample,usestrNametoindicatethattheNamevariablestoresstringdata.ThisnamingmethodiscalledHungariannomenclature.
Formatvariabletype+variablename
Forexample,thestrnamejustmentioned."str"istheabbreviationof"string"."Name"isthenameofthevariable.
Notethatvariabletypesarealllowercaseandvariablenamesarecapitalizedatthebeginning
C#metoda pojmenování
stringstrName
Metoda VB pojmenování
DimstrNameasString
Althoughyoudon’tneedtopaytoomuchattentiontothedetailsofcharacterabbreviations,youstillneedtolookattheconventionsinthisregardinthefuture.ThedetailsofthisagreementcanbefoundintheVisualBasiconlinehelpandmanyVisualBasicadvancedprogrammingbooks.
Období přežití
Thetimethevariableexistsiscalledthesurvivalperiod.ThelifetimeofaScript-levelvariablestartsfromthemomentitisdeclareduntiltheendofthescript.Forprocess-levelvariables,thelifetimeisonlythetimetheprocessruns.Aftertheprocessends,thevariablesdisappear.Duringtheexecutionprocess,localvariablesareidealtemporarystoragespace.Localvariableswiththesamenamecanbeusedindifferentprocedures,becauseeachlocalvariableisonlyrecognizedbytheprocedureinwhichitisdeclared.
Rozsah
Thescopeofavariableisdeterminedbywhereitisdeclared.Ifavariableisdeclaredinaprocedure,onlythecodeintheprocedurecanaccessorchangethevalueofthevariable.Atthistime,thevariablehasalocalscopeandiscalledaprocedure-levelvariable.Ifthevariableisdeclaredoutsidetheprocedure,thevariablecanberecognizedbyallproceduresintheScript.ItiscalledaScript-levelvariableandhasaScript-levelscope.
Život
referstothewholeprocessofvariableallocationandrecovery,
Typ
AttributevariableandProměnnécreatedbyusersthemselves.
Whenwedesigntheuserinterfaceintheform,vb6willautomaticallycreateasetofvariablesforthegeneratedobjects(includingtheformitself),namelyattributevariables,andseteachvariableItsdefaultvalue.Suchvariablescanbeuseddirectlybyus,suchasreferencingitorassigningnewvaluestoit.
Userscanalsocreatetheirownvariablestostoretemporarydataorresultdataduringprogramexecution,etc.Intheprogram,suchvariablesareveryneeded.Thefollowingdescribeshowtocreateandusesuchvariables.
Deklarované proměnné
Před použitím proměnné musíte deklarovat v kódu, tedy vytvořit proměnnou.
Beforeusingvariables,mostlanguagesusuallyfirstneedtodeclarevariables.Inotherwords,thecompilermustbetoldinadvancewhichvariablesareusedintheprogram,aswellasthedatatypesofthesevariablesandthelengthofthevariables.Thisisbecausethecompilerneedstoknowhowtoopenupstorageareasforstatementvariablesbeforethecompiledprogramexecutesthecode,sothattheexecutionoftheprogramcanbeoptimized.
Therearetwowaystodeclarevariables:implicitdeclarationandexplicitdeclaration.
Implicitní prohlášení:
Proměnnécanbeuseddirectlywithoutdeclaration.Atthistime,VBassignsdefaulttypesandvaluestothevariables.Thismethodisrelativelysimpleandconvenient.Proměnnécanbenamedandusedintheprogramcodeatanytime,butitisnoteasytocheck.
Explicitní prohlášení:
Použijte prohlášení deklarace k vytvoření proměnných.
Vynuceno explicitně deklarovat proměnné:
Inordertoavoidthetroublecausedbyincorrectvariablenames,userscanspecifythataslongastheyencounteranuncleardeclaration,Asthenameofavariable,VBwillissueanerrorwarning.Themethodistoforceexplicitdeclarationofvariables.Toforceexplicitdeclarationofvariables,justaddthisstatementinthedeclarationsectionoftheclassmodule,formmoduleorstandardmodule:
OptionExplicit
Thisstatementisusedtostipulatethatallvariablesinthismodulemustbedeclaredbeforeuse,thatis,variablescannotbecreatedbyimplicitdeclaration.AfteraddingtheOptionExplicitstatement,VBwillautomaticallycheckwhetherthereareundefinedvariablesintheprogram,andwilldisplayanerrormessagewhenfound.
IfyouwanttoautomaticallyinserttheOptionExplicitstatement,theuseronlyneedstoselectthe"Options"commandinthe"Tools"menu,thenclickthe"Editor"tabinthe"Options"dialogbox,andthenselect"RequireVariableDeclaration"option,sothatVBwillautomaticallyinsertOptionExplicitstatementsinanynewmodules,butonlyinnewlycreatedmodules.Therefore,foranalreadyestablishedmodule,youcanonlymanuallyaddOptionExplicitstatementstoexistingmodules.
Rozsahofthephysicalvariable
Thescopeofthevariabledeterminesthepartofthecodethatcanknowtheexistenceofthevariable.Whenavariableisdeclaredinsideaprocedure,onlythecodeinsidetheprocedurecanaccessorchangethevalueofthatvariable;ithasascopeandislocaltotheprocedure.However,sometimesitisnecessarytouseavariablewithalargerscope,suchasavariablewhosevalueisvalidforallproceduresinthesamemodule,orevenforallproceduresoftheentireapplication.VisualBasicallowsyoutospecifyitsscopewhendeclaringavariable.
Typ úložiště
Weoftendefinesomevariablesintheprogramtosaveandprocessdata.Inessence,avariablerepresentsapieceofoperablememory,anditcanalsobeconsideredasasymbolicrepresentationofmemory.Whenthememoryneedstobeusedintheprogram,acertaintypeofvariablecanbedefined.Atthistime,thecompilerallocatesacertainamountofmemoryspaceaccordingtothedatatypeofthevariable.Theprogramcanaccessthecorrespondingmemorythroughthevariablename.
Ifthedatatypeofthevariabledeterminesthesizeofthecorrespondingmemory,thenthestoragetypeaffectshowthecorrespondingmemoryisused.Theso-calledmethodofuse,specifically,whenandwhereintheprogramcanusethevariable,thatis,thelifecycleandscopeofthevariable.
Firstunderstandsomebasiccommonsense.1.Therearethreeareasinthememorythatcansavevariableswhentheprogramisrunning:staticstoragearea,stackandheap.2.Accordingtothelocationofthevariabledefinition,itcanbedividedintoglobalvariables(variablesdefinedoutsidethefunctionbody)andlocalvariables(variablesdefinedinsidethefunctionbody,includingformalparameters).
Allglobalvariablesandstaticlocalvariables(usingthekeywordstaticwhendefining)arestoredinthestaticstoragearea,whichischaracterizedby:allocatememoryspaceandinitializeitatcompiletime.Duringtherunningoftheprogram,thevariablealwaysexists,andthememoryspacecorrespondingtothevariableisnotreleaseduntiltheendoftheprogram.
Andallnon-staticlocalvariables(alsoknownasautomaticvariables)arestoredinthestack(stack),whichischaracterizedbydynamiccreationwhenthefunctionormodulewherethevariableislocatedisexecuted,andthefunctionormoduleisexecutedWhenfinished,thememoryspacecorrespondingtothevariableisreleased.Inotherwords,everytimeafunctionormoduleisexecuted,thelocalvariableswillbere-allocatedspace.Ifthevariableisnotinitializedwhenitisdefined,thevalueinthevariableisarandomnumber.
Allthememoryallocatedbymalloc(alsoknownasdynamicmemory)isintheheap,anditscharacteristicisthatthedynamicallyallocatedmemoryisgenerallyaccessedthroughpointers.Thatis,thedynamicmemorycanbemanuallyreleasedbyfree,oritcanbeautomaticallyreleasedbythesystemattheendoftheprogram.
Theabovediscussedthelifecycleofvariables,let’slookatthescopebelow.Rozsahreferstothevisiblerangeofthevariable,thatis,duringthelifecycleofthevariable,whichpartsoftheprogramcanusethevariable.
Thescopeofglobalvariablesstartsatthepointofdefinitionandendsattheendofthesourcefile.Ifyouwanttouseglobalvariablesbeforethepointofdefinition,youneedtousethekeywordexterntoexpandthescope.Bydefault,globalvariablescanbereferencedbyotherfiles.Ifyouwanttobelimitedtothisfile,youneedtousethekeywordstaticwhendefiningit.
Forlocalvariables,whetheritisastaticlocalvariableoranautomaticvariable,thescopeislimitedtothefunctionormodulethatdefinesthevariable.
Aslongasthedynamicmemoryisnotreleased,itcanbeusedanywhereintheprogram,providedthattheaddressofthedynamicmemoryisknown.
Poznámka:Addingstaticbeforeglobalvariablesaffectsthescope,andaddingbeforelocalvariablesaffectsthelifecycle.
Typ proměnné
InClanguage,variablesaredividedintoglobalvariablesandlocalvariables;itcanalsobedividedinto:automaticvariables,staticvariables.Theformerisdividedaccordingtothescopeofthevariable,Thelatterisdividedaccordingtothevariablestoragemethod.
IntheClanguage,ifitisdividedaccordingtothestoragespace,itincludes:
Celočíselné proměnné(codeisint),celočíselnéproměnnézahrnujídlouhécelkovéproměnné(kód jedlouhý)akrátkočíselnéproměnné(kód je krátký),charakterové proměnné(kód je znak),proměnné s plovoucí desetinnou čárkou(kód plovoucí),atd.
Clanguagehasanotherimportantvariable:pointervariable.Thevalueitstoresisamemoryaddress.VariablenamesinClanguagearecase-sensitive.Forexample,SUNandsunaretwodifferentvariablenames.
Anotherpoint,whendeclaringavariable,youcandirectlyassignavaluetodeterminethelanguageofthevariabletypewithoutdeclaration.Thedeclarationofthistypeoflanguagevariableisusuallycalledaweaktype,andsuchas(c++,etc.)mustbedeclaredfirst.Lateruse,andthevariabletypemustbedeterminedwhendeclaring,thisisastrictdatatype.
Therearetwotypesofvariables:AttributevariablesandUser-createdvariables.
JavaScript proměnné
Proměnné
Justlikealgebra,JavaScript proměnnéareusedtostorevaluesorexpressions.
Youcangivethevariableashortname,suchasx,oramoredescriptivename,suchaslength.
JavaScript proměnnécanalsostoretextvalues,suchascarname="Volvo".
Pravidla pro názvy proměnných
Proměnnéarecasesensitive(yandYaretwoDifferentvariables)
Proměnnémuststartwithlettersorunderscores
Poznámka:SinceJavaScriptiscase-sensitive,variablenamesarealsocase-sensitive.
Příklad
Duringtheexecutionofthescript,thevalueofthevariablecanbechanged.Youcanrefertoavariablebyitsnametodisplayorchangeitsvalue.
Tento příklad vám ukazuje princip.
DeclaringProměnné
CreatingvariablesinJavaScriptisoftencalled"declaring"variables.
YoucandeclareJavaScript proměnnéthroughthevarstatement:
varx;varcarname;
varx;varcarname;
Aftertheabovedeclaration,thevariableshavenovalues,butyoucanassignvaluestothevariableswhenyoudeclarethem:
varx=5;varcarname="Volvo";
varx=5;varcarname="Volvo";
Poznámka:Whenassigningatextvaluetoavariable,pleasequotethevalue.
VariableAssignment
AssignavaluetoJavaScriptvariablethroughassignmentstatement:
x=5;carname="Volvo";
x=5;carname="Volvo";
Thevariablenameisontheleftsideofthe=symbol,andthevaluetobeassignedtothevariableisontherightsideofthe=.
Aftertheabovestatementisexecuted,thevaluestoredinthevariablexis5,andthevalueofcarnameisVolvo.
Přiřadit hodnotu nedeklarované proměnné
Ifthevariableyouassignhasnotbeendeclared,thevariablewillbedeclaredautomatically.
Tato prohlášení:
x=5;carname="Volvo";
x=5;carname="Volvo";
Stejný účinek jako tato prohlášení:
varx=5;varcarname="Volvo";
varx=5;varcarname="Volvo";
Znovu deklarujte proměnnou
IfyoudeclareaJavaScriptvariableagain,thevariablewillnotloseitsoriginalvalue.
varx=5;varx;
varx=5;varx;
Aftertheabovestatementisexecuted,thevalueofvariablexisstill5.Whenthevariableisredeclared,thevalueofxwillnotberesetorcleared.
JavaScriptaritmetika
Justlikealgebra,youcanuseJavaScript proměnnétodoarithmetic:
y=x-5;z=y+5;
y=x-5;z=y+5
phpproměnné
Proměnné v PHP: proměnné se používají k ukládání hodnot, jako jsou čísla, textové řetězce nebo pole.
Onceavariableisset,wecanuseitrepeatedlyinthescript.
Všechny proměnné v PHP začněte symbolem $.
Správný způsob nastavení proměnných v PHP:
$var_name=value;Začátečníci PHP zapomenou na symbol $ před proměnnou. Pokud to uděláte, proměnná bude neplatná.
Wecreateavariablewithastringandavariablewithavalue:
ItisnotnecessarytodeclarethedatatypeofthevariabletoPHP.
Accordingtothewaythevariableisset,PHPwillautomaticallyconvertthevariabletothecorrectdatatype.
Inastronglytypedprogramminglanguage,youmustdeclarethetypeandnameofthevariablebeforeusingit.
InPHP,variablesareautomaticallydeclaredwhentheyareused.
Proměnnéinphparerepresentedbyadollarsignfollowedbythevariablename.Variablenamesarecasesensitive.
Názvy proměnných se řídí stejnými pravidly jako jiné značky v php. Platný název proměnné začíná upozorněním nebo podtržítkem, za nímž následuje libovolný počet písmen, čísel nebo podtržítek. Podle běžného regulárního výrazu bude vyjádřen jako:'[a-zA-Z_/x7f-/-xff]7'[a-9/xff]]*.
Poznámka:Thelettersmentionedherearea-z,A-Z,andASCIIcharactersfrom127to255(0x7f-0xff).
Inphp3,variablesarealwaysassignedbyvalue.Thatistosay,whenthevalueofanexpressionisassignedtoavariable,thevalueoftheentireoriginalexpressionisassignedtothetargetvariable.Thismeansthat,forexample,whenthevalueofonevariableisassignedtoanothervariable,changingthevalueofonevariablewillnotaffecttheothervariable.Forthistypeofassignmentoperation,seethechapteronexpressions.
phpprovidesanotherwaytoassignvaluestovariables:referenceassignment.Thismeansthatthenewvariablesimplyreferences(inotherwords,"becomesanalias"or"pointsto")theoriginalvariable.Changingthenewvariablewillaffecttheoriginalvariable,andviceversa.Thisalsomeansthatnocopyoperationisperformed;therefore,thisassignmentoperationisfaster.Butonlyindenseloopsorwhenassigningvaluestoverylargearraysorobjectsisitpossibletonoticethespeedincrease.
Usingreferenceassignment,simplyadda&symbolbeforethevariabletobeassigned(sourcevariable).Forexample,thefollowingcodesnippetwilloutput"MynameisBob"twice:
Oneimportantthingtopointoutisthatonlynamedvariablescanbereferencedandassigned.
Pravidla pro pojmenovávání proměnných
Názvy proměnných musí začínat se znaménkem nebo podtržítkem „_“.
Variablenamescanonlycontainalphanumericcharactersandunderscores.
Názvy proměnných nesmějí obsahovat mezery. Pokud se název proměnné skládá z více slov, měl by být oddělen podtržítky (například $ můj_řetězec) nebo začít velkým písmenem (například $ můj_řetězec).