Logical AND (&&) - JavaScript - MDN Web Docs

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

Short-circuit evaluation ... The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of ... SkiptomaincontentSkiptosearchSkiptoselectlanguageWebtechnologyfordevelopersJavaScriptJavaScriptreferenceExpressionsandoperatorsLogicalAND(&&)ChangelanguageSyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoLogicalAND(&&)ThelogicalAND(&&)operator(logicalconjunction)forasetofBooleanoperandswillbetrueifandonlyifalltheoperandsaretrue.Otherwiseitwillbefalse. Moregenerally,theoperatorreturnsthevalueofthefirstfalsyoperandencounteredwhenevaluatingfromlefttoright,orthevalueofthelastoperandiftheyarealltruthy.Syntaxexpr1&&expr2 DescriptionLogicalAND(&&)evaluatesoperandsfromlefttoright,returningimmediatelywiththevalueofthefirstfalsyoperanditencounters;ifallvaluesaretruthy,thevalueofthelastoperandisreturned. Ifavaluecanbeconvertedtotrue,thevalueisso-calledtruthy.Ifavaluecanbeconvertedtofalse,thevalueisso-calledfalsy. Examplesofexpressionsthatcanbeconvertedtofalseare: false; null; NaN; 0; emptystring(""or''or``); undefined. TheANDoperatorpreservesnon-Booleanvaluesandreturnsthemastheyare: result=''&&'foo';//resultisassigned""(emptystring) result=2&&0;//resultisassigned0 result='foo'&&4;//resultisassigned4 Eventhoughthe&&operatorcanbeusedwithnon-Booleanoperands,itisstillconsideredabooleanoperatorsinceitsreturnvaluecanalwaysbe convertedtoabooleanprimitive. Toexplicitlyconvertitsreturnvalue(oranyexpressioningeneral)tothecorrespondingbooleanvalue,useadoubleNOToperatorortheBooleanconstructor. Short-circuitevaluation ThelogicalANDexpressionisashort-circuitoperator. Aseachoperandisconvertedtoaboolean,iftheresultofoneconversionisfoundtobefalse,theANDoperatorstopsandreturnstheoriginalvalueofthatfalsyoperand;itdoesnotevaluateanyoftheremainingoperands. Considerthepseudocodebelow. (somefalsyexpression)&&expr Theexprpartisneverevaluatedbecausethefirstoperand(somefalsyexpression)isevaluatedasfalsy. Ifexprisafunction,thefunctionisnevercalled. Seetheexamplebelow: functionA(){console.log('calledA');returnfalse;} functionB(){console.log('calledB');returntrue;} console.log(A()&&B()); //logs"calledA"totheconsoleduetothecallforfunctionA, //&&evaluatestofalse(functionAreturnsfalse),thenfalseisloggedtotheconsole; //theANDoperatorshort-circuitshereandignoresfunctionB OperatorprecedenceTheANDoperatorhasahigherprecedencethantheORoperator,meaningthe&&operatorisexecutedbeforethe||operator(seeoperatorprecedence). false||true&&true//returnstrue true&&(false||false)//returnsfalse (2==3)||(4<0)&&(1==1)//returnsfalse ExamplesUsingAND Thefollowingcodeshowsexamplesofthe&&(logicalAND) operator. a1=true&&true//t&&treturnstrue a2=true&&false//t&&freturnsfalse a3=false&&true//f&&treturnsfalse a4=false&&(3==4)//f&&freturnsfalse a5='Cat'&&'Dog'//t&&treturns"Dog" a6=false&&'Cat'//f&&treturnsfalse a7='Cat'&&false//t&&freturnsfalse a8=''&&false//f&&freturns"" a9=false&&''//f&&freturnsfalse ConversionrulesforbooleansConvertingANDtoOR Thefollowingoperationinvolvingbooleans: bCondition1&&bCondition2 isalwaysequalto: !(!bCondition1||!bCondition2) ConvertingORtoAND Thefollowingoperationinvolvingbooleans: bCondition1||bCondition2 isalwaysequalto: !(!bCondition1&&!bCondition2) RemovingnestedparenthesesAslogicalexpressionsareevaluatedlefttoright,itisalwayspossibletoremoveparenthesesfromacomplexexpressionprovidedthatcertainrulesarefollowed. Thefollowingcompositeoperationinvolvingbooleans: bCondition1||(bCondition2&&bCondition3) isalwaysequalto: bCondition1||bCondition2&&bCondition3 SpecificationsSpecificationECMAScriptLanguageSpecification(ECMAScript)#prod-LogicalANDExpressionBrowsercompatibilityBCDtablesonlyloadinthebrowserSeealso Boolean Truthy Falsy Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Dec3,2021,byMDNcontributorsChangeyourlanguageSelectyourpreferredlanguageEnglish(US)Français日本語中文(简体)ChangelanguageRelatedTopics 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 escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8ArrayInternalErrorIntlisFinite()isNaN()JSONMapMathNaNnullNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined unescape() uneval()URIErrorWeakMapWeakRefWeakSetWebAssembly Expressions&operators Additionassignment(+=)Addition(+)Assignment(=)asyncfunctionexpressionawaitBitwiseANDassignment(&=)BitwiseAND(&)BitwiseNOT(~)BitwiseORassignment(|=)BitwiseOR(|)BitwiseXORassignment(^=)BitwiseXOR(^)classexpressionCommaoperator(,)Conditional(ternary)operatorDecrement(--)deleteoperatorDestructuringassignmentDivisionassignment(/=)Division(/)Equality(==)Exponentiationassignment(**=)Exponentiation(**)function*expressionFunctionexpressionGreaterthanorequal(>=)Greaterthan(>)Groupingoperator()inoperatorIncrement(++)Inequality(!=)instanceofLeftshiftassignment(<<=)Leftshift(<>=)Rightshift(>>)Spreadsyntax(...)Strictequality(===)Strictinequality(!==)Subtractionassignment(-=)Subtraction(-)superthistypeofUnarynegation(-)Unaryplus(+)Unsignedrightshiftassignment(>>>=)Unsignedrightshift(>>>)voidoperatoryield*yield Statements&declarations asyncfunctionblockbreakclassconstcontinuedebuggerdo...whileemptyexportforawait...offor...infor...offorfunction*functiondeclarationif...elseimport.metaimportlabelletreturnswitchthrowtry...catchvarwhile with Functions TheargumentsobjectArrowfunctionexpressionsDefaultparametersgetterMethoddefinitionsRestparameterssetter Classes ClassstaticinitializationblocksconstructorextendsPrivateclassfeaturesPublicclassfieldsstatic Errors Warning:-file-isbeingassigneda//#sourceMappingURL,butalreadyhasoneTypeError:invalidArray.prototype.sortargumentWarning:08/09isnotalegalECMA-262octalconstantRangeError:radixmustbeanintegerSyntaxError:invalidregularexpressionflag"x"SyntaxError:returnnotinfunctionTypeError:X.prototype.ycalledonincompatibletypeReferenceError:can'taccesslexicaldeclaration`X'beforeinitializationTypeError:can'taccessproperty"x"of"y"TypeError:can'tassigntoproperty"x"on"y":notanobjectTypeError: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-handsideTypeError: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



請為這篇文章評分?