簡體   English   中英

Javascript:訪問多維數組上的屬性

[英]Javascript: Accessing properties on multidimensional array

我有一個數組,該數組在某個索引處加載具有屬性的數組:

var hotspotLocationsTextAndAudio [];

var myArr = [
[{x:10, y:40, filename:"test",  text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"}]
];

hotspotLocationsTextAndAudio[window.IDNum] = myArr;

要訪問位於hotspotLocationsTextAndAudio的某個索引處的屬性(我的情況是window.IDNum等於)(0)和某個屬性內的數組的索引,我認為我只需要執行以下操作:

alert(hotspotLocationsTextAndAudio[window.IDNum][0].x);

返回未定義。

假設您實際使用的代碼是這樣的:

var hotspotLocationsTextAndAudio [];

var myArr = [
  [{x:10, y:40, filename:"test",  text:"test"}],
  [{x:50, y:60, filename:"test2", text:"test2"]}
];

hotspotLocationsTextAndAudio[window.IDNum] = myArr;

您需要的警報代碼是:

alert(hotspotLocationsTextAndAudio[window.IDNum][0][0].x);

原因是您將對象包裝在[] ,並將它們放置在數組中。

或者,為了使您的原始警報正常工作,您需要將myArr更改為此:

var myArr = [
  {x:10, y:40, filename:"test",  text:"test"},
  {x:50, y:60, filename:"test2", text:"test2"}
];

這對我有用http : //jsfiddle.net/Ku2tQ/

var hotspotLocationsTextAndAudio = [];

var myArr = [
[{x:10, y:40, filename:"test",  text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"}]
];

alert(myArr[1][0].x);

首先,hotspotLocationsTextAndAudio是一個空數組,您永遠不會將myArr推送/合並到該數組。 因此,嘗試訪問空數組的嵌套值將失敗。

arr,也從未定義。

如果可能,請保持簡單,並盡量避免嵌套過多。

暫無
暫無

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

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