4.Operators-操作符(Dart中文文档)

Posted lowezheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4.Operators-操作符(Dart中文文档)相关的知识,希望对你有一定的参考价值。

Dart有如下操作符:

Description Operator
unary postfix expr++ expr-- () [] . ?.
unary prefix -expr !expr ~expr ++expr --expr
multiplicative * / % ~/
additive + -
shift << >>
bitwise AND &
bitwise XOR ^
bitwise OR |
relational and type test >= > <= < as is is!
equality == !=
logical AND &&
logical OR ||
if null ??
conditional expr1 ? expr2 : expr3
cascade ..
assignment = *= /= ~/= %= += -= <<= >>= &= ^= |= ??=

在操作符表中,优先级是从上到下递减。例如,即便&&在==之前,优先级是求余(%)>判断相等(==)> 且(&&)。下面代码中,计算顺序是一致的

// Parentheses improve readability.
if ((n % i == 0) && (d % i == 0)) ...

// Harder to read, but equivalent.
if (n % i == 0 && d % i == 0) ...

注意:操作符左右各有一个对象,操作符具体行为是由左边的对象决定的,这个涉及到操作符重载,比如Vector和Point对象重载了+号操作符的行为,Vector+Point的+号具体行为由Vector决定。

Arithmetic operators 算术运算符

Dart supports the usual arithmetic operators, as shown in the following table.
Dart支持常见的几种算术运算符

Operator Meaning
+ Add
Subtract
-expr Unary minus, also known as negation (reverse the sign of the expression)
* Multiply
/ Divide
~/ Divide, returning an integer result
% Get the remainder of an integer division (modulo)
assert(2 + 3 == 5);
assert(2 - 3 == -1);
assert(2 * 3 == 6);
assert(5 / 2 == 2.5); // Result is a double
assert(5 ~/ 2 == 2); // Result is an int
assert(5 % 2 == 1); // Remainder

assert(‘5/2 = ${5 ~/ 2} r ${5 % 2}‘ == ‘5/2 = 2 r 1‘);

Dart也支持自增自减运算符

Operator Meaning
++var var = var + 1 (expression value is var + 1)
var++ var = var + 1 (expression value is var)
--var var = var – 1 (expression value is var – 1)
var-- var = var – 1 (expression value is var)
var a, b;

a = 0;
b = ++a; // Increment a before b gets its value.
assert(a == b); // 1 == 1

Equality and relational operators 关系运算符

Operator Meaning
== Equal; see discussion below
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

验证两个对象是否相同,用==操作符,(在极少数情况下,你要判断两个对象是否完全相同,需要用identical()函数)
下面是==的判断逻辑:
步骤1.如果x,y都是null,返回true ,x,y只有一个是null,返回false
步骤2.返回x.==(y)的结果,这种写法类似a.method(params),可以将==看做x的方法。

assert(2 == 2);
assert(2 != 3);
assert(3 > 2);
assert(2 < 3);
assert(3 >= 3);
assert(2 <= 3);
a = 0;
b = a++; // Increment a AFTER b gets its value.
assert(a != b); // 1 != 0

a = 0;
b = --a; // Decrement a before b gets its value.
assert(a == b); // -1 == -1

a = 0;
b = a--; // Decrement a AFTER b gets its value.
assert(a != b); // -1 != 0
```
本章节未完











以上是关于4.Operators-操作符(Dart中文文档)的主要内容,如果未能解决你的问题,请参考以下文章

▲Dart-‘dart:html’库

Dart:如何动态设置文档正文innerHTML

7.Classes-类(Dart中文文档)

在 Dart 的 Cloud Firestore 中添加文档后如何获取文档 ID

Dart/Flutter Firestore 查询文档以列出问题

3-2 文档讲解Dart基础快速入门