To readers
This article is the sixth in the " A JSer's Dart Learning Log " series. This series of articles mainly uses the method of mining the similarities and differences between JS and Dart, and makes a smooth transition to the Dart language while reviewing and consolidating JS.
Unless otherwise specified, the JS in this article includes all the features from ES5 to ES2021, and the Dart version is above version 2.0.
Since the author is still a Dart beginner, his understanding may be superficial and one-sided, and the generalization of knowledge will inevitably be overlooked. This series of articles was first published on the Sifu platform. Although there is no restriction on reprinting on other platforms, the errata and new content are limited to Sifu. If you read this article elsewhere, please move to Sifu to avoid seeing the unrevised version. content.
about
Since the digging in this series, the last time I filled it was last year, and to be honest Dart has completely forgotten about it.
Therefore, according to the progress of digging holes before, this article should learn Dart's data collection method Map or List, but temporarily want to consolidate what I have learned before, so try to create something first.
Vector implementation (JS && Dart)
1. class declaration
Use an array/list to store the values of the vector, the advantage of this is that the vector can be any number of dimensions.
js:
class Vector{ #values = []; constructor(values = []){ this.#values = values.map(item => +item); } }
Dart:
class Vector{ List<double> _values; const Vector(this._values); }
2. Convert vector to array/list
Turn the vector into an array/list.
JS:
getValues(){ return this.#values.map(item => item); }
Dart:
List<double> getValues(){ return _values.map((item) => item).toList(); }
3. Read the value of the specified dimension
The dimension here is actually a sequence number, that is, the subscript of the array/list.
js:
getVal(index = 0){ return this.#values[index]; }
Dart
double getVal([int index = 0]){ return _values[index]; }
4. Vector addition
Add two equal-length vectors to get a new vector.
js:
add(obj){ const objVals = obj.getValues(); return this.#values.map((item, index) => item + objVals[index]); }
Dart:
Vector operator +(Vector obj){ final objVals = obj.getValues(); int cnt = 0; return _values.map( (item) => item + objVals[cnt++] ).toList(); }
The subtraction of a vector is a matter of changing the sign, so it is omitted.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。