2012-03-15 68 views
0

我的數組有問題。我創建它們(我不確定是否設計正確),但難以理解如何對它進行檢查。JavaScript多維數組檢查

我的陣列中創建這樣的:

id    = i++; 
uid    = my_id; 
imgwidth  = img[0].width; 
imgheight  = img[0].height; 
spritea[uid] = new Array(); 
spritea[uid][0] = abposx; 
spritea[uid][1] = abposy; 
spritea[uid][2] = imgwidth; 
spritea[uid][3] = imgheight; 

我只是假設這是存儲有關圖像的位置信息,並給它一個唯一的ID的正確方法。

然後我想要做的,按照實施例的標準檢查:

if (x > spritea[0] && x < spritea[0]+spritea[2]){ 
    var uid = //get the UID of the array ; 
} 

但我想我已經構建我的數組錯了嗎?有什麼建議?

回答

2

使用對象。它的清潔:

function create_image(id) { 
    this.id = id; 
    this.height = 0; 
    this.width = 0; 
    this.x = 0; 
    this.y = 0; 
} 

my_image = create_image(++i); 
my_image.width = img[0].width; 
my_image.height = img[0].height; 
my_image.x = abposx; 
my_image.y = abposy;​ 

搜索,試試這個:

found_image = false; 

for (var i = 0; i < spritea.length; i++) { 
    if (spritea[i].width == 4) { 
    found_image = spritea[i]; 
    break; 
    } 
} 

if (found_image) { 
    // found_image is your image 
} 
+0

我該如何做if語句來獲取id? – Sir 2012-03-15 05:31:32

+0

你是什麼意思? – Blender 2012-03-15 05:32:34

+0

如果你看第一篇文章,我試圖通過檢查數組中的值來獲得[uid]值。但我認爲我已經使數組錯誤=/ – Sir 2012-03-15 05:34:24

0

你正在做的測試是不正確的,你需要包括uid

if (x > spritea[someuid][0] && x < spritea[someuid][0]+spritea[someuid][2]){ 

但這可能會更好:

function Image(id, x, y, w, h) 
{ 
    this.width = w; 
    this.height = h; 
    this.x = x; 
    this.y = y; 
    this.IsXInside = function(x) { return (x > this.x && x < (this.x + this.width)); }; 
} 

您創建圖像:

spritea[uid] = new Image(id, abposx, abposy, imgwidth, imgheight); 

然後測試變得

if (sprite[someuid].IsXInside(x)) 
1

看起來像你想的 「精靈」 對象數組

var sprites=[]; 

sprite[123] = { x:aposx, y:aposy, width:imgwidth, height:imgheight }; 

並檢查

var sprite = sprites[1]; 
if (x < sprite.x && sprite.x + sprite.width < x) 
{.... } 
+0

我不能使用sprites [1],因爲[1]的值是我嘗試檢索的內容,又名im試圖通過檢查數組的值來獲取「uid」。哪匹匹配= uid我抓住= /但如果我不能在陣列中使用uid我如何構造數組?有很多uid會被加載,都有自己的信息 – Sir 2012-03-15 05:30:32