Conditional Operator - JavaScript - w3resource
文章推薦指數: 80 %
The conditional operator is used as a shortcut for standard if statement. It takes three operands. ... condition : An expression that evaluates to ... home FrontEnd HTML CSS JavaScript HTML5 Schema.org php.js TwitterBootstrap ResponsiveWebDesigntutorial ZurbFoundation3tutorials PureCSS HTML5Canvas JavaScriptCourse Icon Angular Vue Jest Mocha NPM Yarn BackEnd PHP Python Java Node.js Ruby Cprogramming PHPComposer Laravel PHPUnit Database SQL(2003standardofANSI) MySQL PostgreSQL SQLite NoSQL MongoDB Oracle Redis ApolloGraphQL API GooglePlusAPI YoutubeAPI GoogleMapsAPI FlickrAPI Last.fmAPI TwitterRESTAPI DataInterchnage XML JSON Ajax Exercises HTMLCSSExercises JavaScriptExercises jQueryExercises jQuery-UIExercises CoffeeScriptExercises PHPExercises PythonExercises CProgrammingExercises C#SharpExercises JavaExercises SQLExercises OracleExercises MySQLExercises SQLiteExercises PostgreSQLExercises MongoDBExercises TwitterBootstrapExamples Others ExcelTutorials Usefultools GoogleDocsFormsTemplates GoogleDocsSlidePresentations NumberConversions LinuxTutorials Quizzes Articles HomeJavascriptHome▼JavascriptOperatorsArithmeticOperators(+,-,x,/)ArithmeticOperators(%,++,--,-)AssignmentOperatorsBitwiseOperatorsComparisonOperatorsLogicalOperatorsStringOperators▼SpecialOperatorsConditionaloperatorCommaoperatordeletefunctionininstanceofnewthistypeofvoid JavaScript:ConditionalOperator LastupdateonMay28202210:33:14(UTC/GMT+8hours) ?:(Conditionaloperator) Theconditionaloperatorisusedasashortcutforstandardifstatement.Ittakesthreeoperands. Syntax Condition?expr1:expr2 Parameters condition:Anexpressionthatevaluatestotrueorfalse. expr1,expr2:Expressionswithvaluesofanytypes. Iftheconditionistrue,theoperatorreturnsthevalueofexpr1;otherwise,itreturnsthevalueofexpr2. Forexample status=(marks>=30)?"Pass":"Fail" Thestatementassignsvalue"Pass"tothevariablestatusifmarksare30ormore.Otherwise,itassignsthevalueof"Fail"tostatus. Example: Inthefollowingwebdocumenttheconditionaloperatorstatement[status=(marks>=30)?"Pass":"Fail"]assignsvalue"Pass"tothevariablestatusifmarksare30ormore.Otherwise,itassignsthevalueof"Fail"tostatus. HTMLCode
JSCode functionViewOutput() { 'usestrict'; varmarks=document.getElementById("marks").value; varstatus1=(marks>=30)?"Pass":"Fail"; varnewParagraph=document.createElement("p");//createsanewparagraphelement varnewText=document.createTextNode(status1);//createstextalongwithouputtobedisplayed newParagraph.appendChild(newText);//createdtextisappendedtotheparagraphelementcreated document.body.appendChild(newParagraph);//createdparagraphandtextalongwithoutputisappendedtothedocumentbody } Viewtheexampleinthebrowser JavaScript:ConditionalOperatorandIfelse statement Theconditionaloperatorstatementoftheaboveexample status=(marks>=30)?"Pass":"Fail" isequivalenttothefollowingstatement. ifmarks>=30 document.write("Pass"); else document.write("Fail"); Seealso comma delete function in instanceof new this typeof void WanttoTestyourJavaScriptskill? JavaScriptSkillTest-Level-I JavaScriptSkillTest-Level-II WanttoPracticeJavaScriptexercises? JavaScriptbasic[13ExerciseswithSolution] JavaScriptfunctions[21ExerciseswithSolution] JavaScriptconditionalstatementsandloops[10ExerciseswithSolution] JavaScriptarray[13ExercisewithSolution] JavaScriptregularexpression[6ExerciseswithSolution] JavaScriptHTMLDOM[14ExerciseswithSolution] JavaScriptDrawing[5ExerciseswithSolution] JavaScriptObject[4ExerciseswithSolution] Previous:JavaScript:StringOperators Next:JavaScript:CommaOperator TestyourProgrammingskillswithw3resource'squiz. JavaScript:TipsoftheDay CheckingifakeyexistsinaJavaScriptobject? Checkingforundefined-nessisnotanaccuratewayoftestingwhetherakeyexists.Whatifthekeyexistsbutthevalueisactuallyundefined? varobj={key:undefined}; obj["key"]!==undefined//false,butthekeyexists! Youshouldinsteadusetheinoperator: "key"inobj//true,regardlessoftheactualvalue Ifyouwanttocheckifakeydoesn'texist,remembertouseparenthesis: !("key"inobj)//trueif"key"doesn'texistinobject !"key"inobj//ERROR!Equivalentto"falseinobj" Or,ifyouwanttoparticularlytestforpropertiesoftheobjectinstance(andnotinheritedproperties),usehasOwnProperty: obj.hasOwnProperty("key")//true Checkingforundefined-nessisnotanaccuratewayoftestingwhetherakeyexists.Whatifthekeyexistsbutthevalueisactuallyundefined? varobj={key:undefined}; obj["key"]!==undefined//false,butthekeyexists! Youshouldinsteadusetheinoperator: "key"inobj//true,regardlessoftheactualvalue Ifyouwanttocheckifakeydoesn'texist,remembertouseparenthesis: !("key"inobj)//trueif"key"doesn'texistinobject !"key"inobj//ERROR!Equivalentto"falseinobj" Or,ifyouwanttoparticularlytestforpropertiesoftheobjectinstance(andnotinheritedproperties),usehasOwnProperty: obj.hasOwnProperty("key")//true Forperformancecomparisonbetweenthemethodsthatarein,hasOwnPropertyandkeyisundefined. Ref:https://bit.ly/2CFNp1X NewContentpublishedonw3resource: HTML-CSSPractical:Exercises,Practice,Solution JavaRegularExpression:Exercises,Practice,Solution ScalaProgrammingExercises,Practice,Solution PythonItertoolsexercises PythonNumpyexercises PythonGeoPyPackageexercises PythonPandasexercises Pythonnltkexercises PythonBeautifulSoupexercises FormTemplate Composer-PHPPackageManager PHPUnit-PHPTesting Laravel-PHPFramework Angular-JavaScriptFramework Vue-JavaScriptFramework Jest-JavaScriptTestingFramework
延伸文章資訊
- 1What is Conditional Operator (?:) in JavaScript? - Tutorialspoint
The conditional operator or ternary operator first evaluates an expression for a true or false va...
- 2Conditional Operator - an overview | ScienceDirect Topics
- 3JavaScript Ternary Operator (with Examples) - Programiz
A ternary operator evaluates a condition and executes a block of code based on the condition. Its...
- 4Conditional (ternary) operator - JavaScript - W3cubDocs
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a c...
- 5Conditional Operator - JavaScript - w3resource
The conditional operator is used as a shortcut for standard if statement. It takes three operands...