【发布时间】:2021-09-14 18:13:42
【问题描述】:
我正在观看 freeCodeCamps 数据结构和算法 JavaScript 实现视频 (https://www.youtube.com/watch?v=t2CEgPsws3U),我注意到 Stacks 使用了 this 关键字 (4:49),而他们的集合实现使用了 var (10:06)。
我尝试实现自己的 Sets 实现并收到错误 TypeError: firstSet.forEach is not a function。
- 这是因为我使用了
this而不是var,还是我在实现上犯了错误? - 为什么堆栈实现使用
this而不是var?
我的 Set 实现:
let mySet = function(){
this.collection = [];
this.has = (elem) =>{
return (this.collection.indexOf(elem)!==-1)
}
this.values = ()=>{
return this.collection;
}
this.add = (elem)=>{
if(!this.has(elem)){
this.collection.push(elem)
return true;
}
return false
}
this.remove = (elem)=>{
if(this.has(elem)){
let idx = this.collection.indexOf(elem);
this.collection.splice(idx,1);
return true;
}
return false;
}
this.size = ()=>{
return this.collection.length;
}
this.union = (secondSet)=>{
let unionSet = new mySet();
let firstSet = this.collection.values();
let second = secondSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
})
second.forEach(function(e){
unionSet.add(e)
})
return unionSet;
}
this.intersection = (secondSet)=>{
let intersectionSet = new mySet();
let firstSet = this.collection.values();
let second = secondSet.values();
firstSet.forEach(function(e){
if(second.has(e)){
intersectionSet.add(e);
}
})
return intersectionSet;
}
this.difference = (secondSet)=>{
let differenceSet = new mySet();
let firstSet = this.collection.values();
let second = secondSet.values();
firstSet.forEach(function(e){
if(!second.has(e)){
differenceSet.add(e)
}
})
return differenceSet;
}
this.subset = (secondSet)=>{
let firstSet = this.collection.values();
let second = secondSet.values();
firstSet.every(function(e){
if(second.has(e)){
return true;
}
})
}
}
let mySet1 = new mySet();
let mySet2 = new mySet();
mySet1.add(2)
mySet1.add(3)
mySet1.add(1)
mySet1.add(2)
mySet1.add(5)
mySet2.add(2)
mySet2.add(4);
mySet2.add(6);
console.log(mySet2.union(mySet1))
【问题讨论】:
-
this.collection.values();->this.values();或this.collection。否则你打电话给Array#values
标签: javascript oop data-structures this var