Javascript 和关联数组
Javascript and associative arrays
我是 JS 的新手,所以我尝试使用关联数组,但在我 运行 以下 JS 代码时出现错误。
Uncaught TypeError: Cannot set properties of undefined (setting 'x')
任何帮助都很棒。
var activeField;
fields = []; // holds all the defined fields
function Field() {
this.polypoints = [{}];
}
var field = new Field();
var Points;
fields.push(field);
activeField = (fields.length) - 1;
Points = fields[activeField].polypoints.length;
Points = Points + 1;
fields[activeField].polypoints[Points].x = 1;
fields[activeField].polypoints[Points].y = 1;
console.log("values in array:", activeField, polyPoints, fields);
当您创建 Points=Points+1;
时,Points
现在是 1。fields[activeField].polypoints[Points]
未定义 b/c 您还没有创建对象。该对象位于 fields[activeField].polypoints[0]
。要添加对象,您必须创建。
fields[activeField].polypoints[Points]={x:1,y:1}
我是 JS 的新手,所以我尝试使用关联数组,但在我 运行 以下 JS 代码时出现错误。
Uncaught TypeError: Cannot set properties of undefined (setting 'x')
任何帮助都很棒。
var activeField;
fields = []; // holds all the defined fields
function Field() {
this.polypoints = [{}];
}
var field = new Field();
var Points;
fields.push(field);
activeField = (fields.length) - 1;
Points = fields[activeField].polypoints.length;
Points = Points + 1;
fields[activeField].polypoints[Points].x = 1;
fields[activeField].polypoints[Points].y = 1;
console.log("values in array:", activeField, polyPoints, fields);
当您创建 Points=Points+1;
时,Points
现在是 1。fields[activeField].polypoints[Points]
未定义 b/c 您还没有创建对象。该对象位于 fields[activeField].polypoints[0]
。要添加对象,您必须创建。
fields[activeField].polypoints[Points]={x:1,y:1}