向量类型

向量类型

pubdate:2019-07-09 09:53:57
tags:习题,JavaScript
题目:​编写一个 Vec 类,它表示二维空间中的一个向量。它接受 x 和 y 参数(数字),并将其保存到对象的同名属性中。​向 Vec 原型添加两个方法:plus 和 minus,它们接受另一个向量作为参数,分别返回两个向量(一个是 this,另一个是参数)的和向量与差向量。​向原型添加一个 getter 属性 length,用于计算向量长度,即点(x,y)与原点(0,0)之间的距离。
解:
javascript
// Your code here. class Vec{ constructor(x,y){ this.x=x this.y=y } plus(vec){ return new Vec(this.x+vec.x,this.y+vec.y) } minus(vec){ return new Vec(this.x-vec.x,this.y-vec.y) } get length(){ return Math.sqrt(this.x**2+this.y**2) } } console.log(new Vec(1, 2).plus(new Vec(2, 3))); // → Vec{x: 3, y: 5} console.log(new Vec(1, 2).minus(new Vec(2, 3))); // → Vec{x: -1, y: -1} console.log(new Vec(3, 4).length); // → 5