променлива

Преглед на променливите

Променливиareveryusefulbecausetheyallowyoutoassignashort,easy-to-remembernametoeverypieceofdatayouintendtouseintheprogram.Променливиcansavethedataenteredbytheuserwhentheprogramisrunning(forexample,usetheInputBoxfunctiontodisplayadialogboxonthescreen,andthensavethetexttypedbytheuserintothevariable),theresultofaspecificoperation,andapieceofdatatobedisplayedontheform,etc..Inshort,variablesaresimpletoolsfortrackingalmostalltypesofinformation.

Ifthereisnoassignmentafterthevariabledeclaration,thecompilerwillautomaticallypromptandassignadefaultvalue.

Променливиareconvenientplaceholdersforreferencingcomputermemoryaddresses,whichcanstoreprograminformationthatcanbechangedwhileScriptisrunning.Forexample,youcancreateavariablenamedClickCounttostorethenumberoftimestheuserclicksanobjectontheWebpage.Tousevariables,youdonotneedtoknowtheaddressofthevariableinthecomputer'smemory.Youcanvieworchangethevalueofthevariableaslongasyourefertothevariablebyitsname.ThereisonlyonebasicdatatypeinVBScript,namelyVariant,sothedatatypeofallvariablesisVariant.

Правила за именуване

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.

Забележка:

(1)VariablenamesarenotcasesensitiveinVB(suchasABC,aBc,abc,etc.).Clanguageiscasesensitive.Differentlanguages​​havedifferentrules.

(2)Whendefiningandusingvariables,usuallydefinethevariablenameasanamethatiseasytouseandreadandcandescribetheusefulnessofthecontaineddata,insteadofusingsomedifficultabbreviationssuchasAorB2.Forexample:Supposeyouarecompilingasoftwareforsellingapplesforthefruitshop.WeneedtwovariablestostorethepriceandsalesofApple.Atthispoint,youcandefinetwovariablesnamedApple_PriceandApple_Sold.Eachtimetheprogramisrun,theuserprovidesspecificvalues​​forthesetwovariables,whichlooksveryintuitive.Thespecificmethodis:Makethemeaningofthevariableclearbyformingameaningfulvariablenamewithoneormorewords.Forexample,thevariablenameSalesTaxRateismuchclearerthanTaxorRate.

(3)Mixuppercaseandlowercaselettersandnumbersasneeded.Areasonableagreementistocapitalizethefirstletterofeachwordinthevariable,forexample:DateOfBirth.

(4)Anotherreasonableagreementisthateachvariablenamestartswithatwo-orthree-characterabbreviation,whichcorrespondstothedatatypeofthevariabletobestored.Forexample,usestrNametoindicatethattheNamevariablestoresstringdata.ThisnamingmethodiscalledHungariannomenclature.

Тип променлива на формат+име на променлива

Forexample,thestrnamejustmentioned."str"​​istheabbreviationof"string"."Name"isthenameofthevariable.

Notethatvariabletypesarealllowercaseandvariablenamesarecapitalizedatthebeginning

C#метод за именуване

stringstrName

Метод на именуване на VB

DimstrNameasString

Althoughyoudon’tneedtopaytoomuchattentiontothedetailsofcharacterabbreviations,youstillneedtolookattheconventionsinthisregardinthefuture.ThedetailsofthisagreementcanbefoundintheVisualBasiconlinehelpandmanyVisualBasicadvancedprogrammingbooks.

Период на оцеляване

Thetimethevariableexistsiscalledthesurvivalperiod.ThelifetimeofaScript-levelvariablestartsfromthemomentitisdeclareduntiltheendofthescript.Forprocess-levelvariables,thelifetimeisonlythetimetheprocessruns.Aftertheprocessends,thevariablesdisappear.Duringtheexecutionprocess,localvariablesareidealtemporarystoragespace.Localvariableswiththesamenamecanbeusedindifferentprocedures,becauseeachlocalvariableisonlyrecognizedbytheprocedureinwhichitisdeclared.

Обхват

Thescopeofavariableisdeterminedbywhereitisdeclared.Ifavariableisdeclaredinaprocedure,onlythecodeintheprocedurecanaccessorchangethevalueofthevariable.Atthistime,thevariablehasalocalscopeandiscalledaprocedure-levelvariable.Ifthevariableisdeclaredoutsidetheprocedure,thevariablecanberecognizedbyallproceduresintheScript.ItiscalledaScript-levelvariableandhasaScript-levelscope.

Живот

referstothewholeprocessofvariableallocationandrecovery,

Тип

AttributevariableandПроменливиcreatedbyusersthemselves.

Whenwedesigntheuserinterfaceintheform,vb6willautomaticallycreateasetofvariablesforthegeneratedobjects(includingtheformitself),namelyattributevariables,andseteachvariableItsdefaultvalue.Suchvariablescanbeuseddirectlybyus,suchasreferencingitorassigningnewvalues​​toit.

Userscanalsocreatetheirownvariablestostoretemporarydataorresultdataduringprogramexecution,etc.Intheprogram,suchvariablesareveryneeded.Thefollowingdescribeshowtocreateandusesuchvariables.

Деклариране на променливи

Преди да използвате променливата, трябва да я декларирате в кода, който създава променливата.

Beforeusingvariables,mostlanguages​​usuallyfirstneedtodeclarevariables.Inotherwords,thecompilermustbetoldinadvancewhichvariablesareusedintheprogram,aswellasthedatatypesofthesevariablesandthelengthofthevariables.Thisisbecausethecompilerneedstoknowhowtoopenupstorageareasforstatementvariablesbeforethecompiledprogramexecutesthecode,sothattheexecutionoftheprogramcanbeoptimized.

Therearetwowaystodeclarevariables:implicitdeclarationandexplicitdeclaration.

Неявна декларация:

Променливиcanbeuseddirectlywithoutdeclaration.Atthistime,VBassignsdefaulttypesandvalues​​tothevariables.Thismethodisrelativelysimpleandconvenient.Променливиcanbenamedandusedintheprogramcodeatanytime,butitisnoteasytocheck.

Изрична декларация:

Използвайте declarationstatement за създаване на променливи.

Принудени да декларират променливи изрично:

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.

Обхватofthephysicalvariable

Thescopeofthevariabledeterminesthepartofthecodethatcanknowtheexistenceofthevariable.Whenavariableisdeclaredinsideaprocedure,onlythecodeinsidetheprocedurecanaccessorchangethevalueofthatvariable;ithasascopeandislocaltotheprocedure.However,sometimesitisnecessarytouseavariablewithalargerscope,suchasavariablewhosevalueisvalidforallproceduresinthesamemodule,orevenforallproceduresoftheentireapplication.VisualBasicallowsyoutospecifyitsscopewhendeclaringavariable.

Тип съхранение

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.Обхватreferstothevisiblerangeofthevariable,thatis,duringthelifecycleofthevariable,whichpartsoftheprogramcanusethevariable.

Thescopeofglobalvariablesstartsatthepointofdefinitionandendsattheendofthesourcefile.Ifyouwanttouseglobalvariablesbeforethepointofdefinition,youneedtousethekeywordexterntoexpandthescope.Bydefault,globalvariablescanbereferencedbyotherfiles.Ifyouwanttobelimitedtothisfile,youneedtousethekeywordstaticwhendefiningit.

Forlocalvariables,whetheritisastaticlocalvariableoranautomaticvariable,thescopeislimitedtothefunctionormodulethatdefinesthevariable.

Aslongasthedynamicmemoryisnotreleased,itcanbeusedanywhereintheprogram,providedthattheaddressofthedynamicmemoryisknown.

Забележка:Addingstaticbeforeglobalvariablesaffectsthescope,andaddingbeforelocalvariablesaffectsthelifecycle.

Тип променлива

InClanguage,variablesaredividedintoglobalvariablesandlocalvariables;itcanalsobedividedinto:automaticvariables,staticvariables.Theformerisdividedaccordingtothescopeofthevariable,Thelatterisdividedaccordingtothevariablestoragemethod.

IntheClanguage,ifitisdividedaccordingtothestoragespace,itincludes:

Целочислени променливи(codeisint),целочислени променлививключват дълги цялочислови променливи(codeislongint)икъси цялочисловипроменливи(codeisshortint),символни променливи(codeischar),променливи с плаваща запетая(codefloat) и т.н. Разбира се, има масиви, структурни променливи и т.н.

Clanguagehasanotherimportantvariable:pointervariable.Thevalueitstoresisamemoryaddress.VariablenamesinClanguagearecase-sensitive.Forexample,SUNandsunaretwodifferentvariablenames.

Anotherpoint,whendeclaringavariable,youcandirectlyassignavaluetodeterminethelanguageofthevariabletypewithoutdeclaration.Thedeclarationofthistypeoflanguagevariableisusuallycalledaweaktype,andsuchas(c++,etc.)mustbedeclaredfirst.Lateruse,andthevariabletypemustbedeterminedwhendeclaring,thisisastrictdatatype.

Therearetwotypesofvariables:AttributevariablesandUser-createdvariables.

JavaScript променливи

Променливи

Justlikealgebra,JavaScript променливиareusedtostorevalues​​orexpressions.

Youcangivethevariableashortname,suchasx,oramoredescriptivename,suchaslength.

JavaScript променливиcanalsostoretextvalues,suchascarname="Volvo".

Правила за имена на променливи

Променливиarecasesensitive(yandYaretwoDifferentvariables)

Променливиmuststartwithlettersorunderscores

Забележка:SinceJavaScriptiscase-sensitive,variablenamesarealsocase-sensitive.

Пример

Duringtheexecutionofthescript,thevalueofthevariablecanbechanged.Youcanrefertoavariablebyitsnametodisplayorchangeitsvalue.

Този пример показва принципа на вас.

DeclaringПроменливи

CreatingvariablesinJavaScriptisoftencalled"declaring"variables.

YoucandeclareJavaScript променливиthroughthevarstatement:

varx;име на varcar;

varx;име на varcar;

Aftertheabovedeclaration,thevariableshavenovalues,butyoucanassignvalues​​tothevariableswhenyoudeclarethem:

varx=5;varcarname="Volvo";

varx=5;varcarname="Volvo";

Забележка:Whenassigningatextvaluetoavariable,pleasequotethevalue.

VariableAssignment

AssignavaluetoJavaScriptvariablethroughassignmentstatement:

x=5;carname="Волво";

x=5;carname="Волво";

Thevariablenameisontheleftsideofthe=symbol,andthevaluetobeassignedtothevariableisontherightsideofthe=.

Aftertheabovestatementisexecuted,thevaluestoredinthevariablexis5,andthevalueofcarnameisVolvo.

Присвояване на стойност на недекларирана променлива

Ifthevariableyouassignhasnotbeendeclared,thevariablewillbedeclaredautomatically.

Тези твърдения:

x=5;carname="Волво";

x=5;carname="Волво";

Същият ефект като тези изявления:

varx=5;varcarname="Volvo";

varx=5;varcarname="Volvo";

Декларирайте отново променливата

IfyoudeclareaJavaScriptvariableagain,thevariablewillnotloseitsoriginalvalue.

varx=5;varx;

varx=5;varx;

Aftertheabovestatementisexecuted,thevalueofvariablexisstill5.Whenthevariableisredeclared,thevalueofxwillnotberesetorcleared.

JavaScript аритметика

Justlikealgebra,youcanuseJavaScript променливиtodoarithmetic:

y=x-5;z=y+5;

y=x-5;z=y+5

phpпроменливи

Променливи в PHP: променливите се използват за съхраняване на стойности, като числа, текстови низове или масиви.

Onceavariableisset,wecanuseitrepeatedlyinthescript.

Всички променливи в PHP започват със символа $.

Правилният начин за задаване на променливи в PHP е:

$var_name=стойност;PHP-начинаещите ще забравят$символа отпред на променливата. Ако направите това, променливата ще бъде невалидна.

Wecreateavariablewithastringandavariablewithavalue:

ItisnotnecessarytodeclarethedatatypeofthevariabletoPHP.

Accordingtothewaythevariableisset,PHPwillautomaticallyconvertthevariabletothecorrectdatatype.

Inastronglytypedprogramminglanguage,youmustdeclarethetypeandnameofthevariablebeforeusingit.

InPHP,variablesareautomaticallydeclaredwhentheyareused.

Променливиinphparerepresentedbyadollarsignfollowedbythevariablename.Variablenamesarecasesensitive.

Имената на променливите следват същите правила като други етикети в PHP. Валидното име на променлива започва с буква или долна черта, последвана от произволен брой букви, цифри или долна черта. Съгласно нормалния регулярен израз, то ще бъде изразено като: '[a-zA-Z_/x7f-/xff][a-zA-Z0-9_/x7f-/xff]*'.

Забележка:Thelettersmentionedherearea-z,A-Z,andASCIIcharactersfrom127to255(0x7f-0xff).

Inphp3,variablesarealwaysassignedbyvalue.Thatistosay,whenthevalueofanexpressionisassignedtoavariable,thevalueoftheentireoriginalexpressionisassignedtothetargetvariable.Thismeansthat,forexample,whenthevalueofonevariableisassignedtoanothervariable,changingthevalueofonevariablewillnotaffecttheothervariable.Forthistypeofassignmentoperation,seethechapteronexpressions.

phpprovidesanotherwaytoassignvalues​​tovariables:referenceassignment.Thismeansthatthenewvariablesimplyreferences(inotherwords,"becomesanalias"or"pointsto")theoriginalvariable.Changingthenewvariablewillaffecttheoriginalvariable,andviceversa.Thisalsomeansthatnocopyoperationisperformed;therefore,thisassignmentoperationisfaster.Butonlyindenseloopsorwhenassigningvalues​​toverylargearraysorobjectsisitpossibletonoticethespeedincrease.

Usingreferenceassignment,simplyadda&symbolbeforethevariabletobeassigned(sourcevariable).Forexample,thefollowingcodesnippetwilloutput"MynameisBob"twice:

Oneimportantthingtopointoutisthatonlynamedvariablescanbereferencedandassigned.

Правила за именуване на променливи

Имената на променливите трябва да започват с буква или долна черта "_".

Variablenamescanonlycontainalphanumericcharactersandunderscores.

Имената на променливите не могат да съдържат интервали. Ако името на променливата се състои от няколко думи, то трябва да бъде разделено с долни черти (като $my_string) или да започва с главна буква (като $myString).

Related Articles
TOP