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
}

これが私が立ち往生している場所です:

特定の itemType の画像を初めて挿入したときに「true」に設定するブール変数を作成するにはどうすればよいですか? 同じタイプの画像を 2 回挿入しないようにするために、これが必要です。

簡単な dom ルックアップを実行できることはわかっていますが、javascript を学習しようとしており、この状況でそれを回避する方法を理解したいと考えています。

itemType に基づいて変数を作成し、一致する itemType を持つオブジェクトが assignImage に渡されたときにその変数を変更するスマートな方法は何でしょうか?

4

2 に答える 2

1

名前の先頭に大文字を使用してクラスに名前を付けるという標準の Javascript 規則に従うためだけに、クラス itemType を Item に名前変更しました。以下は、単純な辞書を使用して既に作成されている項目タイプを追跡する方法です。

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);
    }
}
于 2013-10-17T12:03:58.313 に答える
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);
});
于 2013-10-17T12:13:03.170 に答える