javascript - 过滤无效的对象数组

标签 javascript jquery

我的目标

我正在尝试检查集合的所有实例是否都属于特定玩家。这是我的尝试,我不知道我做错了什么。

因此,在我的对象数组中,我只想查看 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/

相关文章:

javascript - 使用 window.location.hostname 时生成意外的 URL

javascript - 循环访问站点上的链接并单击链接 javascript/jquery

javascript - 如何在输入标签内显示div?

javascript - JQuery .post() 将 html 返回到表中

javascript - Jquery promise 等待 ajax 结束

javascript - Web Worker - 使用 Bower 打包时如何引用工作文件

javascript - 使 HTML5 可拖动项目滚动页面?

javascript - 设置innerHTML 的函数调用不起作用 - 给出未定义

javascript - 无法使用 Angular js将数据从json数据获取到纯文本(表)

javascript - Angular 2 调试问题