條件運算子- JavaScript
文章推薦指數: 80 %
JavaScript Demo: Expressions - Conditional operator. xxxxxxxxxx. 1. function getFee(isMember) {. 2. return (isMember ? '$2.00' : '$10.00');. SkiptomaincontentSkiptosearchSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript參考文件運算式與運算子條件運算子ArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.嘗試一下語法描述規範瀏覽器相容性參見RelatedTopics JavaScript Tutorials: Completebeginners JavaScriptbasics JavaScriptfirststeps JavaScriptbuildingblocks IntroducingJavaScriptobjects JavaScriptGuide Introduction Grammarandtypes Controlflowanderrorhandling Loopsanditeration Functions Expressionsandoperators Numbersanddates Textformatting Regularexpressions Indexedcollections Keyedcollections Workingwithobjects Detailsoftheobjectmodel Usingpromises Iteratorsandgenerators Metaprogramming JavaScriptmodules Intermediate Client-sideJavaScriptframeworks Client-sidewebAPIs Are-introductiontoJavaScript JavaScriptdatastructures Equalitycomparisonsandsameness Closures Advanced Inheritanceandtheprototypechain Strictmode JavaScripttypedarrays MemoryManagement ConcurrencymodelandEventLoop References: Built-inobjects AggregateErrorArrayArrayBufferAsyncFunctionAtomicsBigIntBigInt64ArrayBigUint64ArrayBooleanDataViewDatedecodeURI()decodeURIComponent()encodeURI()encodeURIComponent()Error Deprecated escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8ArrayInternalErrorIntlisFinite()isNaN()JSONMapMathNaNNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined Deprecated unescape()URIErrorWeakMapWeakRefWeakSetWebAssembly Expressions&operators Addition(+)Additionassignment(+=)Assignment(=)asyncfunctionexpressionawaitBitwiseAND(&)BitwiseANDassignment(&=)BitwiseNOT(~)BitwiseOR(|)BitwiseORassignment(|=)BitwiseXOR(^)BitwiseXORassignment(^=)classexpressionCommaoperator(,)Conditional(ternary)operatorDecrement(--)deleteoperatorDestructuringassignmentDivision(/)Divisionassignment(/=)Equality(==)Exponentiation(**)Exponentiationassignment(**=)Functionexpressionfunction*expressionGreaterthan(>)Greaterthanorequal(>=)Groupingoperator()importimport.metainoperatorIncrement(++)Inequality(!=)instanceofLeftshift(<>)Rightshiftassignment(>>=)Spreadsyntax(...)Strictequality(===)Strictinequality(!==)Subtraction(-)Subtractionassignment(-=)superthistypeofUnarynegation(-)Unaryplus(+)Unsignedrightshift(>>>)Unsignedrightshiftassignment(>>>=)voidoperatoryieldyield* Statements&declarations asyncfunctionblockbreakclassconstcontinuedebuggerdo...whileemptyexportforforawait...offor...infor...offunctiondeclarationfunction*if...elseimportlabelletreturnswitchthrowtry...catchvarwhile Deprecated with Functions TheargumentsobjectArrowfunctionexpressionsDefaultparametersgetterMethoddefinitionsRestparameterssetter Classes ClassstaticinitializationblocksconstructorextendsPrivateclassfeaturesPublicclassfieldsstatic Errors Warning:-file-isbeingassigneda//#sourceMappingURL,butalreadyhasoneTypeError:invalidArray.prototype.sortargumentWarning:08/09isnotalegalECMA-262octalconstantRangeError:radixmustbeanintegerSyntaxError:invalidregularexpressionflag"x"SyntaxError:returnnotinfunctionRangeError:BigIntdivisionbyzeroRangeError:BigIntnegativeexponentTypeError:X.prototype.ycalledonincompatibletypeReferenceError:can'taccesslexicaldeclaration'X'beforeinitializationTypeError:can'taccessproperty"x"of"y"TypeError:can'tassigntoproperty"x"on"y":notanobjectRangeError:xcan'tbeconvertedtoBigIntbecauseitisn'tanintegerTypeError:can'tconvertBigInttonumberTypeError:can'tconvertxtoBigIntTypeError:can'tdefineproperty"x":"obj"isnotextensibleTypeError:property"x"isnon-configurableandcan'tbedeletedTypeError:can'tredefinenon-configurableproperty"x"TypeError:cyclicobjectvalueTypeError:can'taccessdeadobjectSyntaxError:applyingthe'delete'operatortoanunqualifiednameisdeprecatedReferenceError:deprecatedcallerorargumentsusageWarning:expressionclosuresaredeprecatedSyntaxError:"0"-prefixedoctalliteralsandoctalescapeseq.aredeprecatedSyntaxError:Using//@toindicatesourceURLpragmasisdeprecated.Use//#insteadWarning:String.xisdeprecated;useString.prototype.xinsteadWarning:Date.prototype.toLocaleFormatisdeprecatedSyntaxError:testforequality(==)mistypedasassignment(=)?TypeError:settinggetter-onlyproperty"x"SyntaxError:Unexpected'#'usedoutsideofclassbodySyntaxError:identifierstartsimmediatelyafternumericliteralSyntaxError:illegalcharacterTypeError:cannotuse'in'operatortosearchfor'x'in'y'RangeError:invalidarraylengthReferenceError:invalidassignmentleft-handsideSyntaxError:invalidBigIntsyntaxTypeError:invalidassignmenttoconst"x"RangeError:invaliddateSyntaxError:for-inloopheaddeclarationsmaynothaveinitializersSyntaxError:adeclarationintheheadofafor-ofloopcan'thaveaninitializerTypeError:invalid'instanceof'operand'x'TypeError:'x'isnotiterableSyntaxError:JSON.parse:badparsingSyntaxError:MalformedformalparameterURIError:malformedURIsequenceSyntaxError:missing]afterelementlistSyntaxError:missing:afterpropertyidSyntaxError:missing}afterfunctionbodySyntaxError:missing}afterpropertylistSyntaxError:missingformalparameterSyntaxError:missing=inconstdeclarationSyntaxError:missingnameafter.operatorSyntaxError:missing)afterargumentlistSyntaxError:missing)afterconditionSyntaxError:missing;beforestatementTypeError:MoreargumentsneededRangeError:repeatcountmustbenon-negativeTypeError:"x"isnotanon-nullobjectTypeError:"x"hasnopropertiesSyntaxError:missingvariablenameTypeError:can'tdeletenon-configurablearrayelementRangeError:argumentisnotavalidcodepointTypeError:"x"isnotaconstructorTypeError:"x"isnotafunctionReferenceError:"x"isnotdefinedRangeError:precisionisoutofrangeError:Permissiondeniedtoaccessproperty"x"TypeError:"x"isread-onlySyntaxError:redeclarationofformalparameter"x"TypeError:ReduceofemptyarraywithnoinitialvalueSyntaxError:"x"isareservedidentifierRangeError:repeatcountmustbelessthaninfinityWarning:unreachablecodeafterreturnstatementSyntaxError:"usestrict"notallowedinfunctionwithnon-simpleparametersInternalError:toomuchrecursionReferenceError:assignmenttoundeclaredvariable"x"ReferenceError:referencetoundefinedproperty"x"SyntaxError:UnexpectedtokenTypeError:"x"is(not)"y"SyntaxError:functionstatementrequiresanameSyntaxError:unterminatedstringliteral Misc JavaScripttechnologiesoverview Lexicalgrammar JavaScriptdatastructures Enumerabilityandownershipofproperties Iterationprotocols Strictmode Transitioningtostrictmode Templateliterals Deprecatedfeatures 嘗試一下語法描述規範瀏覽器相容性參見條件運算子嘗試一下 條件(三元)運算子是JavaScript唯一用到三個運算元的運算子:在一個條件後面會跟著一個問號(?),如果條件是truthy,在冒號(:)前的表達式會被執行,如果條件是falsy,在冒號後面的表達式會被執行,這個運算子常常被用來當作if的簡潔寫法. 語法condition?exprIfTrue:exprIfFalse參數 condition 值用來做為條件的表達式 exprIfTrue 如果condition的值是truthy(等於或是可轉換為true),exprIfTrue會被執行 exprIfFalse 如果condition的值是falsy(等於或是可轉換為false),exprIfFalse會被執行 描述除了false,可能是falsy的表達式有null,NaN,0,空字串("")和undefined.如果condition是他們其中之一,那麼條件表達式的結果會是exprIfFalse的執行結果. 一個簡單的範例: varage=26; varbeverage=(age>=21)?"Beer":"Juice"; console.log(beverage);//"Beer" 一個常用來處理null的用法: functiongreeting(person){ varname=person?person.name:"stranger"; return"Howdy,"+name; } console.log(greeting({name:'Alice'}));//"Howdy,Alice" console.log(greeting(null));//"Howdy,stranger" 條件鏈條件(三元)運算子是右相依性的(right-associative),代表他可以以下面的方式鏈結,類似於if…elseif …elseif…else的鏈結方法: functionexample(…){ returncondition1?value1 :condition2?value2 :condition3?value3 :value4; } //Equivalentto: functionexample(…){ if(condition1){returnvalue1;} elseif(condition2){returnvalue2;} elseif(condition3){returnvalue3;} else{returnvalue4;} } 規範SpecificationECMAScriptLanguageSpecification#sec-conditional-operator瀏覽器相容性BCDtablesonlyloadinthebrowser參見 ifstatement Nullishcoalescingoperator Optionalchaining Makingdecisionsinyourcode—conditionals Expressionsandoperators Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:2022年6月30日,byMDNcontributors
延伸文章資訊
- 1What is a Ternary Operator? - Computer Hope
The ternary operator is an operator that exists in some programming languages, which takes three ...
- 2Ternary Operator in C Explained - freeCodeCamp
Programmers use the ternary operator for decision making in place of longer if and else condition...
- 3Ternary Operator -?: - Wikipedia
- 4條件運算子- JavaScript
JavaScript Demo: Expressions - Conditional operator. xxxxxxxxxx. 1. function getFee(isMember) {. ...
- 5JavaScript Ternary Operator (with Examples) - Programiz
What is a Ternary operator? ... A ternary operator evaluates a condition and executes a block of ...