Conditional Operator - JavaScript - w3resource

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

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

JavaScriptconditionaloperatorexamplewithDOM

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



請為這篇文章評分?