我有一些JavaScript從數組中抓取座標。Js獲取未捕獲TypeError:無法讀取未定義的屬性,但仍然工作
我得到的錯誤是檢索變量的右側和左側座標。
該錯誤是
Uncaught TypeError: Cannot read property 'rightX' of undefined
代碼是
var notesArray = ["A","Bf","B","C","Cs","D","Ef","E","F","Fs","G","Gs"];
notesArray["A"] = {leftX : 0, rightX : 320, topY : 0, bottomY : 240, color : "#ffffff"};
notesArray["Bf"] = {leftX : 0, rightX : 320, topY : 240, bottomY : 480, color : "#ffffff"};
notesArray["B"] = {leftX : 320, rightX : 640, topY : 0, bottomY : 240, color: "#ffffff"};
notesArray["C"] = {leftX : 0, rightX : 320, topY : 480, bottomY : 720, color: "#ffffff"};
notesArray["Cs"] = {leftX : 320, rightX : 640, topY : 240, bottomY : 480, color: "#ffffff"};
notesArray["D"] = {leftX : 640, rightX : 960, topY : 0, bottomY : 240, color: "#ffffff"};
notesArray["Ef"] = {leftX : 320, rightX : 640, topY : 480, bottomY : 720, color: "#ffffff"};
notesArray["E"] = {leftX : 640, rightX : 960, topY : 240, bottomY : 480, color: "#ffffff"};
notesArray["F"] = {leftX : 960, rightX : 1280, topY : 0, bottomY : 240, color: "#ffffff"};
notesArray["Fs"] = {leftX : 640, rightX : 960, topY : 480, bottomY : 720, color: "#ffffff"};
notesArray["G"] = {leftX : 960, rightX : 1280, topY : 240, bottomY : 480, color: "#ffffff"};
notesArray["Gs"] = {leftX : 960, rightX : 1280, topY : 480, bottomY : 720, color: "#ffffff"};
...
// do something in here
var n = (note.slice(0,2)) ? note.slice(0,2) : "D" ;
x = Math.floor(Math.random() * (notesArray[n].rightX - notesArray[n].leftX + 1)) + notesArray[n].leftX;
y = Math.floor(Math.random() * (notesArray[n].bottomY - notesArray[n].topY + 1)) + notesArray[n].topY;
n個可變和notesArray [N]的控制檯日誌.rightX
因此,它是得到數字,它是它正在查找的任何變量的rightX的座標,並且實際上正在工作operly。我的問題是,爲什麼(或如何)拋出這個錯誤,但返回正確的座標,無論如何修復我的代碼,所以它不會拋出錯誤?
我可能會丟失這個,但是'note'是什麼定義的? – War10ck
您的第一行將'notesArray'初始化爲一個數組。但接下來的12行分配給屬性,就好像它是一個對象。雖然允許數組擁有屬性,但這是一種不常見的模式,我懷疑這不是您真正想要的。 – Barmar
發生這種情況時'n'的值是多少? – Barmar