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
Type test operators 类操作符
Operator | Meaning |
---|---|
as | Typecast (also used to specify library prefixes) |
is | True if the object has the specified type |
is! | False if the object has the specified type |
如果对象A是实现T这个类的,那么 A is T == true,is!正好相反。as的用法是将对象A强制转换为指定类型。 | |
下面的例子是判断对象类型,如果是true,可执行对应类型的方法 |
if (emp is Person) {
// Type check
emp.firstName = 'Bob';
}
这是上面的简化写法,如果emp是null或者不是Person类型,后续代码不会执行
(emp as Person).firstName = 'Bob';
Assignment operators 赋值运算符
As you’ve already seen, you can assign values using the = operator. To assign only if the assigned-to variable is null, use the ??= operator.
如你所知,可以用=进行赋值,如果只对空对象赋值,可以用??=。
// Assign value to a
a = value;
// Assign value to b if b is null; otherwise, b stays the same
b ??= value;
组合赋值操作符:
= |–= |/= |%= |>>= |^=
+= |*= |~/= |<<= |&=| ||=
等效说明:
Compound assignment | Equivalent expression | |
---|---|---|
For an operator op: | a op= b | a = a op b |
Example: | a += b | a = a + b |
The following example uses assignment and compound assignment operators: |
var a = 2; // Assign using =
a *= 3; // Assign and multiply: a = a * 3
assert(a == 6);
```
### Logical operators 逻辑运算符
|Operator| Meaning|
|--|--|
!expr |inverts the following expression (changes false to true, and vice versa)
|| |logical OR
&& |logical AND
下面是逻辑运算符示例:
···
if (!done && (col == 0 || col == 3)) {
// ...Do something...
}
···
### Bitwise and shift operators 位和移位操作符
你可以对数值进行移位操作
Operator| Meaning
--|--
|&| AND
\|| OR
^| XOR
~expr| Unary bitwise complement (0s become 1s; 1s become 0s)
<<| Shift left
>>| Shift right
下面是移位操作示例:
```
final value = 0x22;
final bitmask = 0x0f;
assert((value & bitmask) == 0x02); // AND
assert((value & ~bitmask) == 0x20); // AND NOT
assert((value | bitmask) == 0x2f); // OR
assert((value ^ bitmask) == 0x2d); // XOR
assert((value << 4) == 0x220); // Shift left
assert((value >> 4) == 0x02); // Shift right
```
### Conditional expressions 条件表达式
Dart有两种条件表达式写法,来取代if逻辑。
```
condition ? expr1 : expr2
```
如果condition是true,返回expr1,否则返回expr2
```
expr1 ?? expr2
```
如果expr1不是null,返回expr1,否则返回expr2.
```
var visibility = isPublic ? 'public' : 'private';
String playerName(String name) => name ?? 'Guest';
```
```
// Slightly longer version uses ?: operator.
String playerName(String name) => name != null ? name : 'Guest';
// Very long version uses if-else statement.
String playerName(String name) {
if (name != null) {
return name;
} else {
return 'Guest';
}
}
```
### Cascade notation (..) 链式调用操作符
链式操作符允许你对相同对象进行多次调用而不用多次写对象名。
```
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
```
上面的示例等效于:
```
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
```
You can also nest your cascades. For example:
```
final addressBook = (AddressBookBuilder()
..name = 'jenny'
..email = 'jenny@example.com'
..phone = (PhoneNumberBuilder()
..number = '415-555-0100'
..label = 'home')
.build())
.build();
```
注意,链式调用必须由对象发起,比如下面的write返回值为void,所以无法使用链式调用。
```
var sb = StringBuffer();
sb.write('foo')
..write('bar'); // Error: method 'write' isn't defined for 'void'.
```
### Other operators 其它操作符
Operator| Name| Meaning
--|--|--
() |Function application| Represents a function call
[] |List access |Refers to the value at the specified index in the list
. |Member access |Refers to a property of an expression; example: foo.bar selects property bar from expression foo
?. |Conditional |member access Like ., but the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)
第四篇准备翻译 Control flow statements 流程控制