基于对象属性的布尔变量

时间:2013-10-17 11:58:28

标签: javascript

我完全陷入了可能非常基本的事情:

我正在使用构造函数来创建几个游戏项目:

function itemCreator(itemName, itemType, itemPosition) {
            this.itemName = itemName;
            this.itemType = itemType;
            this.itemPosition =itemPosition;
}

 new itemCreator('shootUp001', 'item_up', 108 );

 new itemCreator('shootLeft001', 'item_left', 608);

 new itemCreator('shootLeft002', 'item_left', 40);

后来我正在为这样的项目分配图像:

function assignImages(item){
    itemObject =item;
    itemType = itemObject.itemType;
    var itemDiv = document.getElementById(itemType); //get the div that has the name of this item
    itemDiv.innerHTML = '<img src="' +itemType +'.png"/><span class="x">x</span><span id="' +itemType +'SpanCount"></span>' //put the picture of this item in there and also a span for the counting
}

这就是我被困的地方:

当我第一次插入某个itemType的图像时,如何创建一个设置为“true”的布尔变量?我需要这个以避免两次插入相同类型的图像。

我知道我可以做一个简单的dom查找,但我正在尝试学习javascript,并想了解在这种情况下如何避免这种情况。

那么,当assignImage传递一个匹配itemType的对象时,基于itemType创建变量并修改该变量的智能方法是什么?

2 个答案:

答案 0 :(得分:1)

我将您的class itemType重命名为Item只是为了遵循标准的Javascript约定,我们用大写字母命名我们的类来启动名称。下面是我如何跟踪已经使用简单字典创建的项类型:

var images = {};//keeping track of images by item types so far

function assignImages(item){
    var type = item.itemType
    if(!images.hasOwnProperty(type)) {
        var itemDiv = document.getElementById(type); //get the div that has the name of this item
        itemDiv.innerHTML = '<img src="' +type +'.png"/><span class="x">x</span><span id="' +type +'SpanCount"></span>' //put the picture of this item in there and also a span for the counting
        images[type] = itemDiv;
    } else {
        console.warn("A image of item type %s already exists", type);
    }
}

答案 1 :(得分:0)

不应将图像分配给项目,而应将其应用于类型。 获取所有唯一的项目类型,然后将图像分配给那些。

function itemCreator(itemName, itemType, itemPosition) {
            this.itemName = itemName;
            this.itemType = itemType;
            this.itemPosition =itemPosition;
}

function assignImages(itemType){
    var itemDiv = document.getElementById(itemType);
    itemDiv.innerHTML = '<img src="' +itemType +'.png"/><span class="x">x</span><span id="' +itemType +'SpanCount"></span>'
}

var list = [
    new itemCreator('shootUp001', 'item_up', 108),
    new itemCreator('shootLeft001', 'item_left', 608),
    new itemCreator('shootLeft002', 'item_left', 40)
];

var unique_types = list.map(function(i) {
        return i.itemType;
    }).reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);

unique_types.forEach(function(itemType){
    assignImages(itemType);
});