javascript - 即使属性存在也无法读取属性
问题描述
我不明白为什么下面的代码说Cannot read property 'x' of undefined,即使该属性是在其对象定义之后添加的。
let points = [
{ x:0, y:2 },
{ x:10, y:20 },
];
points[3] = { x:3, y:8, z:15 }
console.log(points[3])
// ok until here
points.dist = function() {
let p1 = this[0];
let p2 = this[2];
let a = p2.x-p1.x; let b = p2.y-p1.y;
return Math.sqrt(a*a + b*b);
};
points.dist();
解决方案
您使用跨越索引 0 和 1 的 2 个对象初始化数组。然后您将一个对象添加到索引 3。但是,在dist
函数中,您正在访问索引 2。索引 2 没有定义对象。
let p2 = this[2]; // <-- It should be either 0, 1, or 3; 2 is never defined on array
您可以在使用之前检查数组的结构:
let points = [
{ x:0, y:2 },
{ x:10, y:20 },
];
points[3] = { x:3, y:8, z:15 }
console.log(points);
推荐阅读
- java - 如何在 Android 上的电子邮件中发送附件
- json - 设置 Stripe 支付网关时返回 json 数据时出错。Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
- rest - RestClient.post 响应生成“错误 groovyx.net.http.ResponseParseException:OK”
- c# - 如何将模型中的数据作为数据传递给
- javascript - 单击侧面或退出按钮时下拉菜单必须消失
- php - "message": "方法 Illuminate\\Auth\\SessionGuard::factory 不存在。",
- jakarta-ee - @Alternative 和默认实现 CDI
- java - 线程“main”中的异常 java.util.zip.ZipException:打开 zip 文件时出错 测试应用程序时
- azure - 无法为 Synapse Analytics 调用暂停(工作区预览)
- sql - PostgreSQL 类型为 table/setof 的数组