What is a Ternary Operator? - Computer Hope
文章推薦指數: 80 %
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
延伸文章資訊
- 1條件運算子- JavaScript
JavaScript Demo: Expressions - Conditional operator. xxxxxxxxxx. 1. function getFee(isMember) {. ...
- 2Conditional or Ternary Operator (?:) in C/C++ - GeeksforGeeks
The conditional operator is kind of similar to the if-else statement as it does follow the same a...
- 3?: operator - C# reference | Microsoft Docs
Learn about the C# ternary conditional operator that returns the result of one of the two express...
- 4JavaScript Ternary Operator (with Examples) - Programiz
What is a Ternary operator? ... A ternary operator evaluates a condition and executes a block of ...
- 5Make Your Code Cleaner with JavaScript Ternary Operator
Introduction to JavaScript ternary operator ... In this syntax, the condition is an expression th...