我有一些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