2013-10-17 171 views
1

我完全卡住的东西,可能是很基本的:布尔变量基于对象属性

我使用一个构造函数来创建一些游戏道具:

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 
} 

这里就是我坚持:

我怎么能CREA te是我第一次插入某个itemType的图像时设置为“true”的布尔变量吗?我需要这个来避免两次插入相同类型的图像。

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

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

回答

1

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

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); 
    } 
} 
+0

我没有看到你实际修改'items'的地方? – Pavlo

+0

@Pavlo在Item类的第5行 - 我将项目实例分配给item中的itemType。 – megawac

+0

以下是问题所在:如果我正确读取了代码,则只有在具有相同itemType的项目不存在时才会创建属性。但是我需要所有的项目,不管它们是否具有相同的itemType。我只需要为每个itemType分配一次图像。 –

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); 
}); 
+0

Ouch,我相信这是一个体面的解决方案,但unique_types函数是对我目前的理解说话:/ –