What is a Ternary Operator? - Computer Hope

文章推薦指數: 80 %
投票人數:10人

The ternary operator is an operator that exists in some programming languages, which takes three operands rather than the typical one or two ... SkiptoMainContent HomeDictionaryT-Definitions Ternaryoperator Updated:05/02/2021byComputerHope Theternaryoperatorisanoperatorthatexistsinsomeprogramminglanguages,whichtakesthreeoperandsratherthanthetypicaloneortwothatmostoperatorsuse.Itprovidesawaytoshortenasimpleifelseblock.Forexample,considerthebelowJavaScriptcode. varnum=4,msg="";if(num===4){  msg="Correct!";}else{  msg="Incorrect!";}alert(msg); Ifthenumvariableisequalto4,thentheusergetsa"Correct!"message.Otherwise,theusergetsan"Incorrect!"message.Withthistypeofcomparison,youcanshortenthecodeusingtheternaryoperator.Belowisanexampleofhowitworks. variable_name=(condition)?value_if_true:value_iffalse; Aternaryoperatorallowsyoutoassignonevaluetothevariableiftheconditionistrue,andanothervalueiftheconditionisfalse. Theifelseblockexamplefromabovecouldnowbewrittenasshownintheexamplebelow. varnum=4,msg="";msg=(num===4)?"Correct!":"Incorrect!";alert(msg); Aternaryoperatormakestheassignmentofavaluetoavariableeasiertosee,becauseit'scontainedonasinglelineinsteadofanifelseblock. Operator,Programmingterms,Ternary Wasthispageuseful?YesNoFeedbackE-mailSharePrint



請為這篇文章評分?