PHP 与 JavaScript 的运算符优先级差异

来源:互联网 发布:centos ip forward 编辑:程序博客网 时间:2024/06/07 00:46
两者优先级大部分都一样,比较(comparision)运算和赋值(assignment)运算有细微的差别。比较运算符有 >, <, >= 等等,赋值运算符有 =, +=, *= 等等。
JS 里比较运算符比赋值运算符优先级高。于是 foo = 1 < 2 结果 foo =  false;
PHP 里反过来,赋值运算符比比较运算符优先级高。于是 foo = 1 <  2 结果 foo = 1, 表达式为 false。为达到与上面同样的结果,需加上小括号
foo = (1 < 2)

附:PHP与JavaScript完整的运算符优先级

JS

The following table is ordered from highest (19) to lowest (0) precedence.

PrecedenceOperator typeAssociativityIndividual operators19Groupingn/a( … )18Member Accessleft-to-right… . …Computed Member Accessleft-to-right… [ … ]new (with argument list)n/anew … ( … )17Function Callleft-to-right… ( … )new (without argument list)right-to-leftnew …16Postfix Incrementn/a… ++Postfix Decrementn/a… --15Logical NOTright-to-left! …Bitwise NOTright-to-left~ …Unary Plusright-to-left+ …Unary Negationright-to-left- …Prefix Incrementright-to-left++ …Prefix Decrementright-to-left-- …typeofright-to-lefttypeof …voidright-to-leftvoid …deleteright-to-leftdelete …14Exponentiationright-to-left… ** …Multiplicationleft-to-right… * …Divisionleft-to-right… / …Remainderleft-to-right… % …13Additionleft-to-right… + …Subtractionleft-to-right… - …12Bitwise Left Shiftleft-to-right… << …Bitwise Right Shiftleft-to-right… >> …Bitwise Unsigned Right Shiftleft-to-right… >>> …11Less Thanleft-to-right… < …Less Than Or Equalleft-to-right… <= …Greater Thanleft-to-right… > …Greater Than Or Equalleft-to-right… >= …inleft-to-right… in …instanceofleft-to-right… instanceof …10Equalityleft-to-right… == …Inequalityleft-to-right… != …Strict Equalityleft-to-right… === …Strict Inequalityleft-to-right… !== …9Bitwise ANDleft-to-right… & …8Bitwise XORleft-to-right… ^ …7Bitwise ORleft-to-right… | …6Logical ANDleft-to-right… && …5Logical ORleft-to-right… || …4Conditionalright-to-left… ? … : …3Assignmentright-to-left… = …… += …… -= …… **= …… *= …… /= …… %= …… <<= …… >>= …… >>>= …… &= …… ^= …… |= …2yieldright-to-leftyield …1Spreadn/a... …0

PHP
Operator PrecedenceAssociativityOperatorsAdditional Informationnon-associativeclone newclone andnewleft[array()right**arithmeticright++ -- ~ (int) (float) (string) (array) (object) (bool) @types andincrement/decrementnon-associativeinstanceoftypesright!logicalleft* / %arithmeticleft+ - .arithmetic andstringleft<< >>bitwisenon-associative< <= > >=comparisonnon-associative== != === !== <> <=>comparisonleft&bitwise andreferencesleft^bitwiseleft|bitwiseleft&&logicalleft||logicalright??comparisonleft? :ternaryright= += -= *= **= /= .= %= &= |= ^= <<= >>= =>assignmentleftandlogicalleftxorlogicalleftorlogical 
1 0
原创粉丝点击