我的目标
我正在尝试检查集合
的所有实例是否都属于特定玩家。这是我的尝试,我不知道我做错了什么。
因此,在我的对象数组中,我只想查看 City 对象,然后对照 set
检查 set
属性(作为函数中的参数传递)我想检查,最后检查该集合的每个实例是否具有相同的所有者
。
function test(){
assignOwner();
var set = "brown";
var player = 1;
if(doesOwnSet(set, player)){
console.log("You own the" + set + "set.");
}
else{
console.log("You dont own the set mate.");
}
}
function assignOwner(){
positions[1].owner = 1;
positions[3].owner = 1;
}
function doesOwnSet(set, player){
positions.filter(function(obj){
return (obj.set === set;
})
.every(function(obj){
return (obj.owner === player);
})
}
** 我试图过滤的对象数组**
function Position (title, type, purchasable){
this.title = title;
this.type = type;
this.purchasable = purchasable || false;
}
function Purchasable (prices){
this.owner = "unowned";
this.rating = 0;
this.prices = prices;
this.price = this.prices[this.rating];
}
function Corner (title){
Position.call(this, title, "corner");
}
function CardPosition (title,type){
Position.call(this, title, type);
}
function Tax (title,tax){
Position.call(this, title, "tax");
this.tax = tax;
}
function Utility (title, prices){
Position.call(this, title, "utility", true);
Purchasable.call(this, prices);
}
function Airport(title,prices){
Position.call(this, title, "airport", true);
Purchasable.call(this, prices);
}
function City (title,set,prices){
Position.call(this, title, "city", true);
Purchasable.call(this, prices);
this.set = set;
}
positions = [
new Corner("Go"),
new City("Cairo", "brown", [60,2,10,30,90,160,250]),
new CardPosition("Chest", "chest"),
new City("Vienna", "brown", [60,4,20,60,180,320,450])
];
最佳答案
您需要从 doesOwnSet
方法返回值
function doesOwnSet(set, player) {
return positions.filter(function (obj) {
return (obj.set === set);
}).every(function (obj) {
return (obj.owner === player);
})
}
演示:Fiddle
关于javascript - 过滤无效的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21986245/