第一题
方法一: 构造函数
- 写一个构造函数
function Vec(x,y){
this.x = x,
this.y = y,
}
- 给原型添加方法
Vec.prototype.plus=function(V){ // plus方法
return new Vec(V.x+this.x,V.y+this.y)
}
Vec.prototype.minus=function(V){ // minus方法
return new Vec(this.x-V.x,this.y-V.y)
}
Vec.prototype.getLength=function(){
console.log(Math.sqrt(this.x*this.x+this.y*this.y))
}
// 获取length需要执行 v.getLength() 方法,这个方法其实在原型Vec上
注意: 这其实是违背题意的,这里的getLength其实是原型上的方法,而题上是指读取器属性,后面会给出做法,这只是一种实现。
- length的获取也可以这样
function Vec(x,y){
this.x = x,
this.y = y,
//this.length = Math.sqrt(this.x**2+this.y**2)
this.length = Math.floor(Math.sqrt(this.x**2+this.y**2)*100)/100 //保留两位看起来舒服点
}
Vec.prototype.plus=function(V){ // plus方法
return new Vec(V.x+this.x,V.y+this.y)
}
Vec.prototype.minus=function(V){ // minus方法
return new Vec(this.x-V.x,this.y-V.y)
}
// 获取length的方式变成了 v.length
- 试一试
const v1 = new Vec(2,2) //创建向量v1
const v2 = new Vec(2,2) //创建向量v2
const v3 = v1.plus(v2) //向量v3 = v1+v2
const v4 = v1.minus(v3) // v4 = v1 - v3
console.log(v1,v2,v3,v4)
console.log(v4.length)
结果:
这里使用的是在线编译器codepen
*方法二: 类
其实这才是题中所指的实现方法吧
class Vec{
constructor(x,y){
this.x = x,
this.y = y
}
get length(){
return Math.floor(Math.sqrt(this.x**2+this.y**2)*100)/100
}
}
Vec.prototype.plus=function(V){ // plus方法
return new Vec(V.x+this.x,V.y+this.y)
}
Vec.prototype.minus=function(V){ // minus方法
return new Vec(this.x-V.x,this.y-V.y)
}
// 测试结果一致 不再赘述
目前我就想到这么多, 有误的地方欢迎评论区指出
第二题
- 首先我们创建一个Group类, 里面需要存储值,我用数组来模拟
class Group{
constructor(){
this.data = []
}
}
- 写add方法
add(x){
//判断是否存在于组中
if(this.data.includes(x)){
console.log('已存在')
return;
}
this.data.push(x)
}
- 写delete方法
delete(x){
if(this.data.includes(x)){ // 确认组中有要删除的元素
let i = this.data.indexOf(x)
this.data.splice(i,1)
}else console.log(`组中没有找到${x}`)
}
- 写has方法,返回值是boolean
has(x){
return this.data.includes(x)
}
- 静态from方法
static from(list){
let g = new Group
for(let item of list){
g.add(item)
}
return g
}
这只是一个极其简单的实现,因为没有考虑到引用类型!!
- 合并
class Group{
constructor(){
this.data = []
}
add(x){
//判断是否存在于组中
if(this.data.includes(x)){
console.log('已存在')
return;
}
this.data.push(x)
}
delete(x){
if(this.data.includes(x)){
let i = this.data.indexOf(x)
this.data.splice(i,1)
}else console.log(`组中没有找到${x}`)
}
has(x){
return this.data.includes(x)
}
static from(list){
let g = new Group
for(let item of list){
g.add(item)
}
return g
}
}
- 测试
const g = new Group()
g.add(1)
g.add(2)
g.add(3)
g.add(2)
console.log(g)
//" 2已存在 [1,2,3] "
g.delete(3) // [1,2]
g.has(2) // true
const g2 = Group.from([1,5,3,1,3])
// g2 --- [1,5,3] 已经去重了
这就行了?重点来了!
const g3 = Group.from([1,2,[3,4],[3,4],2])
// 我们用一个数组创建Group 数组中有5个元素: 1 , 2 ,[3,4], [3,4] , 2
// 很明显 [3,4] [3,4] 这俩跟一个妈生的似的,完全一样,应该去重吧?
console.log(g3)
// [1,2,[3,4],[3,4]]
两个重复的 2 去掉了一个,但是这俩数组元素咋还在里面呢?
答: 在初始化组的时候,使用add方法添加
而 add 方法主要靠 includes 判断数据是否相同
但是! includes 和 indexOf 都只能判断基本数据类型
如果想判断引用数据类型需要另写逻辑
如果这里到位了,其实对深浅拷贝也就理解了
我选择…抛砖引玉
有方案的可以评论区讨论一下,我再学习学习
第三题
第四题
逐渐无法理解,等我学透了再来做吧