首页 > 解决方案 > 即使属性存在也无法读取属性

问题描述

我不明白为什么下面的代码说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();

标签: javascriptfunctionproperties

解决方案


您使用跨越索引 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);


推荐阅读