变量order / side与关系运算符有什么区别?

时间:2021-08-14 01:11:17

Compare:

if (donald_duck != null)
if (roast_potatoes > 9000)
if (love === 'explosions')

and

if (null != donald_duck)
if (9000 <= roast_potatoes)
if ('explosions' === love)

In the languages I've written in, I've always used the first order since it makes sense human-wise. e.g. "Is the parrot dead?" vs "Is dead what the parrot is?" However I've seen the (null == variable) order used a few times in various languages and places.

在我写的语言中,我总是使用第一个顺序,因为它在人类方面是有意义的。例如“鹦鹉死了吗?” vs“死了鹦鹉是什么?”但是我已经看到(null == variable)命令在各种语言和地方使用了几次。

What operational difference does it make, and is one way more syntactically correct or widely adopted?

它有什么操作上的区别,并且在语法上更正确或被广泛采用?

(I'm aware this may be different for various languages, so in particular I'm asking in regards to PHP)

(我知道各种语言可能会有所不同,所以特别是我对PHP的问题)

1 个解决方案

#1


There is no different in the behavior but it helps to avoid errors for example in the comparisons.

行为没有区别,但它有助于避免错误,例如在比较中。

if you use obj == null to compare, you have some risk of making a mistake and putobj = null instead causing problems in your code and having unexpected results.

如果使用obj == null进行比较,则存在出错的风险,putobj = null会导致代码出现问题并产生意外结果。

But if you use null == obj to compare, that risk goes away because null = obj is not a valid sentence (you can't assign an object to null) and you will receive an error in compile time.

但是如果你使用null == obj进行比较,那么风险就会消失,因为null = obj不是一个有效的句子(你不能将一个对象赋值为null),你将在编译时收到一个错误。

Hope this helps

希望这可以帮助

#1


There is no different in the behavior but it helps to avoid errors for example in the comparisons.

行为没有区别,但它有助于避免错误,例如在比较中。

if you use obj == null to compare, you have some risk of making a mistake and putobj = null instead causing problems in your code and having unexpected results.

如果使用obj == null进行比较,则存在出错的风险,putobj = null会导致代码出现问题并产生意外结果。

But if you use null == obj to compare, that risk goes away because null = obj is not a valid sentence (you can't assign an object to null) and you will receive an error in compile time.

但是如果你使用null == obj进行比较,那么风险就会消失,因为null = obj不是一个有效的句子(你不能将一个对象赋值为null),你将在编译时收到一个错误。

Hope this helps

希望这可以帮助