用TS声明一个二维向量
时间: 2023-05-17 15:07:55 浏览: 83
TypeScript向量和矩阵数学库。_TypeScript_JavaScript_下.zip
可以使用以下代码声明一个二维向量:
```typescript
class Vector2D {
constructor(public x: number, public y: number) {}
add(other: Vector2D): Vector2D {
return new Vector2D(this.x + other.x, this.y + other.y);
}
subtract(other: Vector2D): Vector2D {
return new Vector2D(this.x - other.x, this.y - other.y);
}
multiply(scalar: number): Vector2D {
return new Vector2D(this.x * scalar, this.y * scalar);
}
divide(scalar: number): Vector2D {
return new Vector2D(this.x / scalar, this.y / scalar);
}
get length(): number {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
normalize(): Vector2D {
const length = this.length;
return new Vector2D(this.x / length, this.y / length);
}
}
const v1 = new Vector2D(1, 2);
const v2 = new Vector2D(3, 4);
console.log(v1.add(v2)); // Vector2D { x: 4, y: 6 }
console.log(v1.subtract(v2)); // Vector2D { x: -2, y: -2 }
console.log(v1.multiply(2)); // Vector2D { x: 2, y: 4 }
console.log(v1.divide(2)); // Vector2D { x: 0.5, y: 1 }
console.log(v1.length); // 2.23606797749979
console.log(v1.normalize()); // Vector2D { x: 0.4472135954999579, y: 0.8944271909999159 }
```
阅读全文