本文主要介紹運算符相關(guān)操作
算術(shù)運算符
- 加減乘除:
+
,-
,*
,/
,%
,~/
- 遞增遞減:
var++
,var--
,++var
,--var
double a = 10.0;
double b = 2.0;
print(a + b);
//12.0
print(a - b);
//8.0
print(a * b);
//20.0
print(a / b);
//5.0
print(a % b);
//0.0
print(a ~/ b);
//5
print(a++);
//10.0 a++ 是a使用以后a+1 表達式之后a此時為11.0
print(++a);
//12.0 ++a 是a使用之前a+1 a從 11.0+1 = 12.0
print(a--);
//12.0 a-- 是a使用之后a-1 表達式之后a 此時為11.0
print(--a);
//10.0 --a 是a使用之前a-1 a 從 11.0-1 = 10.0
關(guān)系運算符
- 運算符:
==
,!=
,>
,<
,>=
,<=
- 判斷內(nèi)容是否相同;
==
int a = 5;
int b = 3;
print(a == b);
//false
print(a != b);
//true
print(a > b);
//true
print(a < b);
//false
print(a >= b);
//true
print(a <= b);
//false
String str1 = "123";
String str2 = "123";
String str3 = "321";
print(str1 == str2);
//true
print(str1 == str3);
//false
邏輯運算符
- 運算符:
!
,&&
,||
- 針對布爾型運算
bool isTrue = true;
print(!isTrue);
//false
bool isFalse = false;
print(isTrue && isFalse);
//false 同時為true 才為true
print(isTrue || isFalse);
//true 兩個有一個為true 就為true
String str = "";
print(!str.isEmpty);
//false
賦值運算符
- 基礎(chǔ)運算符:
=
,??=
- 復(fù)合運算符:
+=
,-=
,*=
,/=
,%=
,~/=
int a = 10;
int b = 5;
int c;
b ??= 10;
print(b);
//5 b有值取b的值
c ??= 10;
print(c);
//10 c沒有值,賦值10
a += b; //相當(dāng)于a = a + b;
print(a);
//15
a -= b; //相當(dāng)于a = a - b;
print(a);
//10;
a *= b; //相當(dāng)于a = a * b;
print(a);
//50
// a /= b;//a為int 使用/=是double,所以報錯
a %= b; //相當(dāng)于a = a % b;
print(a);
//0
a ~/= b; //相當(dāng)于a = a ~/ b;
print(a);
//0
條件表達式
- 三目運算符:
condition ? expr1 : expr2
- ??運算符:
expr1 ?? expr2
int gendar = 1;
String str = gendar == 1 ? "Male" : "Female";
print(str);
//Male
String str1 = "Dart";
String str2 = "Java";
String str3;
String str4 = str2 ?? str1;//str2有值取str2,無值取str1
print(str4);
//Java
String str5 = str3 ?? str1;//str3有值取str3,無值取str1
print(str5);
//Dart