Muuttujien yleiskatsaus
Muuttujatareveryusefulbecausetheyallowyoutoassignashort,easy-to-remembernametoeverypieceofdatayouintendtouseintheprogram.Muuttujatcansavethedataenteredbytheuserwhentheprogramisrunning(forexample,usetheInputBoxfunctiontodisplayadialogboxonthescreen,andthensavethetexttypedbytheuserintothevariable),theresultofaspecificoperation,andapieceofdatatobedisplayedontheform,etc..Inshort,variablesaresimpletoolsfortrackingalmostalltypesofinformation.
Ifthereisnoassignmentafterthevariabledeclaration,thecompilerwillautomaticallypromptandassignadefaultvalue.
Muuttujatareconvenientplaceholdersforreferencingcomputermemoryaddresses,whichcanstoreprograminformationthatcanbechangedwhileScriptisrunning.Forexample,youcancreateavariablenamedClickCounttostorethenumberoftimestheuserclicksanobjectontheWebpage.Tousevariables,youdonotneedtoknowtheaddressofthevariableinthecomputer'smemory.Youcanvieworchangethevalueofthevariableaslongasyourefertothevariablebyitsname.ThereisonlyonebasicdatatypeinVBScript,namelyVariant,sothedatatypeofallvariablesisVariant.
Nimeämissäännöt
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.
Huomautus:
(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.
Muotomuuttujan tyyppi+muuttujan nimi
Forexample,thestrnamejustmentioned."str"istheabbreviationof"string"."Name"isthenameofthevariable.
Notethatvariabletypesarealllowercaseandvariablenamesarecapitalizedatthebeginning
C#nimeämismenetelmä
stringstrName
VB-nimeämismenetelmä
DimstrNameasString
Althoughyoudon’tneedtopaytoomuchattentiontothedetailsofcharacterabbreviations,youstillneedtolookattheconventionsinthisregardinthefuture.ThedetailsofthisagreementcanbefoundintheVisualBasiconlinehelpandmanyVisualBasicadvancedprogrammingbooks.
Selviytymisjakso
Thetimethevariableexistsiscalledthesurvivalperiod.ThelifetimeofaScript-levelvariablestartsfromthemomentitisdeclareduntiltheendofthescript.Forprocess-levelvariables,thelifetimeisonlythetimetheprocessruns.Aftertheprocessends,thevariablesdisappear.Duringtheexecutionprocess,localvariablesareidealtemporarystoragespace.Localvariableswiththesamenamecanbeusedindifferentprocedures,becauseeachlocalvariableisonlyrecognizedbytheprocedureinwhichitisdeclared.
Laajuus
Thescopeofavariableisdeterminedbywhereitisdeclared.Ifavariableisdeclaredinaprocedure,onlythecodeintheprocedurecanaccessorchangethevalueofthevariable.Atthistime,thevariablehasalocalscopeandiscalledaprocedure-levelvariable.Ifthevariableisdeclaredoutsidetheprocedure,thevariablecanberecognizedbyallproceduresintheScript.ItiscalledaScript-levelvariableandhasaScript-levelscope.
Elinikä
referstothewholeprocessofvariableallocationandrecovery,
Tyyppi
AttributevariableandMuuttujatcreatedbyusersthemselves.
Whenwedesigntheuserinterfaceintheform,vb6willautomaticallycreateasetofvariablesforthegeneratedobjects(includingtheformitself),namelyattributevariables,andseteachvariableItsdefaultvalue.Suchvariablescanbeuseddirectlybyus,suchasreferencingitorassigningnewvaluestoit.
Userscanalsocreatetheirownvariablestostoretemporarydataorresultdataduringprogramexecution,etc.Intheprogram,suchvariablesareveryneeded.Thefollowingdescribeshowtocreateandusesuchvariables.
Ilmoittavat muuttujat
Ennen kuin käytät muuttujaa, sinun on ilmoitettava koodissa, eli luotava muuttuja.
Beforeusingvariables,mostlanguagesusuallyfirstneedtodeclarevariables.Inotherwords,thecompilermustbetoldinadvancewhichvariablesareusedintheprogram,aswellasthedatatypesofthesevariablesandthelengthofthevariables.Thisisbecausethecompilerneedstoknowhowtoopenupstorageareasforstatementvariablesbeforethecompiledprogramexecutesthecode,sothattheexecutionoftheprogramcanbeoptimized.
Therearetwowaystodeclarevariables:implicitdeclarationandexplicitdeclaration.
Implisiittinen ilmoitus:
Muuttujatcanbeuseddirectlywithoutdeclaration.Atthistime,VBassignsdefaulttypesandvaluestothevariables.Thismethodisrelativelysimpleandconvenient.Muuttujatcanbenamedandusedintheprogramcodeatanytime,butitisnoteasytocheck.
Nimenomainen ilmoitus:
Käytä ilmoituslauseita muuttujien luomiseen.
Pakotettu ilmoittamaan muuttujat nimenomaisesti:
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.
Laajuusofthephysicalvariable
Thescopeofthevariabledeterminesthepartofthecodethatcanknowtheexistenceofthevariable.Whenavariableisdeclaredinsideaprocedure,onlythecodeinsidetheprocedurecanaccessorchangethevalueofthatvariable;ithasascopeandislocaltotheprocedure.However,sometimesitisnecessarytouseavariablewithalargerscope,suchasavariablewhosevalueisvalidforallproceduresinthesamemodule,orevenforallproceduresoftheentireapplication.VisualBasicallowsyoutospecifyitsscopewhendeclaringavariable.
Tallennustyyppi
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.Laajuusreferstothevisiblerangeofthevariable,thatis,duringthelifecycleofthevariable,whichpartsoftheprogramcanusethevariable.
Thescopeofglobalvariablesstartsatthepointofdefinitionandendsattheendofthesourcefile.Ifyouwanttouseglobalvariablesbeforethepointofdefinition,youneedtousethekeywordexterntoexpandthescope.Bydefault,globalvariablescanbereferencedbyotherfiles.Ifyouwanttobelimitedtothisfile,youneedtousethekeywordstaticwhendefiningit.
Forlocalvariables,whetheritisastaticlocalvariableoranautomaticvariable,thescopeislimitedtothefunctionormodulethatdefinesthevariable.
Aslongasthedynamicmemoryisnotreleased,itcanbeusedanywhereintheprogram,providedthattheaddressofthedynamicmemoryisknown.
Huomautus:Addingstaticbeforeglobalvariablesaffectsthescope,andaddingbeforelocalvariablesaffectsthelifecycle.
Muuttujatyyppi
InClanguage,variablesaredividedintoglobalvariablesandlocalvariables;itcanalsobedividedinto:automaticvariables,staticvariables.Theformerisdividedaccordingtothescopeofthevariable,Thelatterisdividedaccordingtothevariablestoragemethod.
IntheClanguage,ifitisdividedaccordingtothestoragespace,itincludes:
Kokonaislukumuuttujat(codeisint),kokonaislukumuuttujatsisältääpitkät kokonaislukumuuttujat(codeislongint)ja lyhyet kokonaismuuttujat(codeisshortint),merkkimuuttujat(codeischar),kelluvapistemuuttujat(codefloat),etc.
Clanguagehasanotherimportantvariable:pointervariable.Thevalueitstoresisamemoryaddress.VariablenamesinClanguagearecase-sensitive.Forexample,SUNandsunaretwodifferentvariablenames.
Anotherpoint,whendeclaringavariable,youcandirectlyassignavaluetodeterminethelanguageofthevariabletypewithoutdeclaration.Thedeclarationofthistypeoflanguagevariableisusuallycalledaweaktype,andsuchas(c++,etc.)mustbedeclaredfirst.Lateruse,andthevariabletypemustbedeterminedwhendeclaring,thisisastrictdatatype.
Therearetwotypesofvariables:AttributevariablesandUser-createdvariables.
JavaScript-muuttujat
Muuttujat
Justlikealgebra,JavaScript-muuttujatareusedtostorevaluesorexpressions.
Youcangivethevariableashortname,suchasx,oramoredescriptivename,suchaslength.
JavaScript-muuttujatcanalsostoretextvalues,suchascarname="Volvo".
Muuttujannimisäännöt
Muuttujatarecasesensitive(yandYaretwoDifferentvariables)
Muuttujatmuststartwithlettersorunderscores
Huomautus:SinceJavaScriptiscase-sensitive,variablenamesarealsocase-sensitive.
Esimerkki
Duringtheexecutionofthescript,thevalueofthevariablecanbechanged.Youcanrefertoavariablebyitsnametodisplayorchangeitsvalue.
Tämä esimerkki osoittaa sinulle periaatteen.
DeclaringMuuttujat
CreatingvariablesinJavaScriptisoftencalled"declaring"variables.
YoucandeclareJavaScript-muuttujatthroughthevarstatement:
varx;varcarname;
varx;varcarname;
Aftertheabovedeclaration,thevariableshavenovalues,butyoucanassignvaluestothevariableswhenyoudeclarethem:
varx=5;varcarname="Volvo";
varx=5;varcarname="Volvo";
Huomautus:Whenassigningatextvaluetoavariable,pleasequotethevalue.
VariableAssignment
AssignavaluetoJavaScriptvariablethroughassignmentstatement:
x=5;carname="Volvo";
x=5;carname="Volvo";
Thevariablenameisontheleftsideofthe=symbol,andthevaluetobeassignedtothevariableisontherightsideofthe=.
Aftertheabovestatementisexecuted,thevaluestoredinthevariablexis5,andthevalueofcarnameisVolvo.
Määritä arvo ilmoittamattomalle muuttujalle
Ifthevariableyouassignhasnotbeendeclared,thevariablewillbedeclaredautomatically.
Nämä lausunnot:
x=5;carname="Volvo";
x=5;carname="Volvo";
Samat vaikutukset kuin lausunnoissa:
varx=5;varcarname="Volvo";
varx=5;varcarname="Volvo";
Ilmoita muuttuja uudelleen
IfyoudeclareaJavaScriptvariableagain,thevariablewillnotloseitsoriginalvalue.
varx=5;varx;
varx=5;varx;
Aftertheabovestatementisexecuted,thevalueofvariablexisstill5.Whenthevariableisredeclared,thevalueofxwillnotberesetorcleared.
JavaScriptaritmetiikka
Justlikealgebra,youcanuseJavaScript-muuttujattodoarithmetic:
y=x-5;z=y+5;
y=x-5;z=y+5
php-muuttujat
PHP:n muuttujia:muuttujia käytetään tallentamaan arvoarvoja, kuten numeroita, tekstijonoja tai taulukoita.
Onceavariableisset,wecanuseitrepeatedlyinthescript.
Kaikki PHP:n muuttujat alkavat $symbolilla.
Oikea tapa asettaa muuttujat PHP:ssä:
$var_name=value;PHPaloittelijat unohtavat $symbolinmuuttujan edessä. Jos teet sen, muuttuja ei kelpaa.
Wecreateavariablewithastringandavariablewithavalue:
ItisnotnecessarytodeclarethedatatypeofthevariabletoPHP.
Accordingtothewaythevariableisset,PHPwillautomaticallyconvertthevariabletothecorrectdatatype.
Inastronglytypedprogramminglanguage,youmustdeclarethetypeandnameofthevariablebeforeusingit.
InPHP,variablesareautomaticallydeclaredwhentheyareused.
Muuttujatinphparerepresentedbyadollarsignfollowedbythevariablename.Variablenamesarecasesensitive.
Muuttujien nimetseuraavat samaa samaa muina tunnisteina php:ssä.Voimassa olevat muuttujien nimet alkavat kirjaimella tai alaviivalla, joita seuraa mikä tahansa määrä kirjaimia, numeroita tai alaviivoja. Normaalin säännöllisen lausekkeen mukaan se ilmaistaan seuraavasti:'[a-zA-Z_/x7f-/xff.
Huomautus: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.
Muuttujien nimeämissäännöt
Muuttujien nimien täytyy alkaa kirjaimella tai alaviivalla"_".
Variablenamescanonlycontainalphanumericcharactersandunderscores.
Jos muuttujan nimi koostuu useista sanoista, se tulisi erotella alaviivillä (kuten$oma_merkkijono)tai aloittaa isolla kirjaimella(kuten$omamerkkijono).