簡體   English   中英

從數組中提取單個值以存儲在變量javascript中

[英]Pulling a single value from an array to store in a variable javascript

因此,我已經看到了幾種方法,但是它們似乎並不能滿足我的期望...

我在另一部分代碼中使用了此推送,但我不明白為什么它不適用於有問題的代碼。

var npc = new Array();

npc.push([  
[5,25,10],
]);

npc.push([  
[18,28,38],
]);

npc.push([  
[1,2,3],
]);

我想進行設置,這樣我可以打電話給...

LoadNpc(2);

我希望它檢查第二個npc數組並將3個數字設置為變量。

hp = 18;
atk = 28;
def = 38;
id = 2;  //current loaded npc's id

我敢肯定,我已經在考慮如何做到這一點,而且我什么也無法正常工作。 如果有人正確使用簡單的JavaScript,我將非常感激。

您應該使用對象數組而不是數組數組。

npc[2] = {hp :18, atk: 28, def :38} 

您可以像這樣“拉”值:

alert(npc[2].atk);
alert(npc[2].hp);
...

這看起來非常簡單:

var npc = [];
npc.push([5,25,10]);
npc.push([18,28,38]);
npc.push([1,2,3]);

var hp, atk, def, id;

function loadNpc(index){
    id = index;
    hp = npc[index-1][0];
    atk = npc[index-1][1];
    def = npc[index-1][2];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM