From JavaScript To Dart

2019-12-16  本文已影响0人  wish_dd

From JavaScript To Dart

Dart 的一些特性

JavaScript to Dart

打印日志

console.log('Hello World')
print('Hello World');

常量与变量

let num = 1;
const num = 1;
int num = 1;
var num = 1;
const num = 1;
final num = 1;

null声明

let lineCount = null;

未初始化的变量默认值是 null

int lineCount;

空判断

if (text) {
    const length = text.length();
}
// If p is non-null, set its y value to 4.
p?.y = 4;

字符串拼接

let firstName = "Amit";
let lastName = "Shekhar";
let message = "My name is: " + firstName + " " + lastName;
var firstName = "Amit";
var lastName = "Shekhar";
var message = "My name is: $firstName $lastName";

换行

let text = "First Line\n" +
              "Second Line\n" +
              "Third Line";
var text = """
        First Line
        Second Line
        Third Line
        """;

三元表达式

let text = x > 5 ? "x > 5" : "x <= 5";
var text = x > 5 ? "x > 5" : "x <= 5";
String playerName = name ?? 'Guest';

操作符

const andResult  = a & b;
const orResult   = a | b;
const xorResult  = a ^ b;
const rightShift = a >> 2;
const leftShift  = a << 2;
const unsignedRightShift = a >>> 2;
var andResult  = a & b;
var orResult   = a | b;
var xorResult  = a ^ b;
var rightShift = a >> 2;
var leftShift  = a << 2;

类型判断和转换 (声明式)

class Person {
  firstName;

  constructor(firstName) {
    this.firstName = firstName;
    console.log(`in Person${firstName}`);
  }
}

class Employee extends Person {

  constructor(firstName) {
    super(firstName);
    console.log(`in Employee${firstName}`);
  }
}

const emp = new Employee('Peter');
emp.firstName = 'Bob';
console.log(emp.firstName);

class Person {
  String firstName;

  Person(this.firstName) {
    print('in Person$firstName');
  }
}

class Employee extends Person {
  Employee(firstName) : super(firstName) {
    print('in Employee$firstName');
  }
}

void main() {
  var emp = new Employee('Peter');
  if (emp is Person) {
    // Type check
    emp.firstName = 'Bob';
  }
  (emp as Person).firstName = 'Bob';
  print(emp.firstName);
}

类型判断和转换 (隐式)

"1" + 2
"1" + 2 // The argument type 'String' can't be assigned to the parameter type 'num'.

集合操作

// Or simply use a list literal.
var fruits = ['apples', 'oranges'];

// Add to a list.
fruits.push('kiwis');

// Add multiple items to a list.
fruits = fruits.concat(['grapes', 'bananas']);
// Remove a single item.
var appleIndex = fruits.indexOf('apples');
fruits.splice(appleIndex, 1);
console.log(fruits);

// Or simply use a list literal.
var fruits = ['apples', 'oranges'];

// Add to a list.
fruits.add('kiwis');

// Add multiple items to a list.
fruits.addAll(['grapes', 'bananas']);
// Remove a single item.
var appleIndex = fruits.indexOf('apples');
fruits.removeAt(appleIndex);
print(fruits);

fruits.clear();
print(fruits.isEmpty);

方法定义

function doSomething() {
   // logic here
}

function doSomething(numbers) {
   // logic here
}
void doSomething() {
   // logic here
}

fun doSomething(List<int> numbers) {
   // logic here
}

带返回值的方法

function getScore() {
   // logic here
   return score;
}
int getScore(int score) {
   // logic here
   return score * 100;
}

// as a single-expression function

int getScore(int score) => score * 100;

constructor 构造器

class Point {
  constructor(x, y) {
    // There's a better way to do this, stay tuned.
    this.x = x;
    this.y = y;
  }
}
class Point {
  num x, y;

  Point(num x, num y) {
    // There's a better way to do this, stay tuned.
    this.x = x;
    this.y = y;
  }
}

// another way

class Point {
  num x, y;

  // Syntactic sugar for setting x and y
  // before the constructor body runs.
  Point(this.x, this.y);
}

Get Set 构造器

class Rectangle {
  left;
  top;
  width;
  height;

  constructor(left, top, width, height) {
    this.left = left;
    this.top = top;
    this.width = width;
    this.height = height;
  }

  // Define two calculated properties: right and bottom.
  get right() {
    return this.left + this.width;
  }

  set right(value) {
    this.left = value - this.width
  }

  get bottom() {
    return this.top + this.height;
  }

  set bottom(value) {
    this.top = value - this.height
  }

}
class Rectangle {
  num left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  // Define two calculated properties: right and bottom.
  num get right => left + width;
  set right(num value) => left = value - width;
  num get bottom => top + height;
  set bottom(num value) => top = value - height;
}

克隆

lodash#clone

dart 不提供通用的 clone 方法,但可以自己实现 clone 方法。

class Foo {
  int id;
  String something;
  List elements;

  Foo(this.id, this.something, this.elements);

  Foo.clone(Foo original)
      : this(original.id, original.something, new List.from(original.elements));

  @override
  String toString() {
    return 'Foo{id: $id, something: $something, elements: $elements}';
  }
}

Class 静态方法

class Utils {
  static triple(value) {
    return 3 * value;
  }
}
class Utils {
  static int triple(int value) {
    return 3 * value;
  }
}

enum

enum Color { red, green, blue }

void main() {
  List<Color> colors = Color.values;
  assert(colors[2] == Color.blue);
}

排序

var fruits = ['bananas', 'apples', 'oranges'];

// Sort a list.
fruits.sort();
var fruits = ['bananas', 'apples', 'oranges'];

// Sort a list.
fruits.sort();

匿名类

let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

Dart 不支持匿名类与内部类。


Union Types

JavaScript 和 Dart 都不支持 Union Types

let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;
上一篇下一篇

猜你喜欢

热点阅读