【问题标题】:Javascript and associative arraysJavascript 和关联数组
【发布时间】:2021-09-27 11:52:07
【问题描述】:

我是 JS 新手,所以我尝试使用关联数组,但在运行以下 JS 代码时出现错误。

未捕获的类型错误:无法设置未定义的属性(设置“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);

【问题讨论】:

  • 关联数组仅存在于 PHP 中。它们在 JavaScript 中的等价物是对象。
  • 应该声明字段 var

标签: javascript associative-array


【解决方案1】:

当您创建Points=Points+1; 时,Points 现在为 1。fields[activeField].polypoints[Points] 未定义 b/c 您尚未创建对象。该对象位于fields[activeField].polypoints[0]。要添加对象,您必须创建。

fields[activeField].polypoints[Points]={x:1,y:1}

【讨论】:

  • (恕我直言)更好的选择是完全跳过Points(因为它不用于其他任何事情)而只跳过.push()新对象。
  • 也很好@Andreas
  • 当我使用:fields[activeField].polypoints.push({x:2, y:2});元素 2 和 2 存储在从 1 开始的数组中,它应该是 0 - 我做错了吗?
  • 似乎数组已经有一个元素@JackStein
猜你喜欢
  • 1970-01-01
  • 2011-08-15
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多