微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未捕获的TypeError:current.distance不是函数

如何解决未捕获的TypeError:current.distance不是函数

我正在开发一个完全没有意义的小游戏,通常称为“寻路”;并且我因一个从未遇到过的小错误而崩溃(我是年轻的开发人员);

我到处搜索过,但不明白为什么会出现此错误

我遇到此错误

未捕获的TypeError:current.distance不是函数 在search_min_distance(pathfinding.js:127) 在游戏中(pathfinding.js:151) 在HTMLDocument。 (pathfinding.js:173)

This have been received:name: age: 

-> current和stk [0]确实是“类型”点。

其余所有代码对我来说似乎并不重要,但如有必要,我会提供。

我先谢谢你!放纵...

解决方法

使用getElement函数得到的点仅返回 js对象,它不包含该类中的任何函数。

您需要从获取的点开始在search_min_distance函数内创建一个新的类实例

const { x,y,name,id } = current;
const currentPoint = new Point(x,id);
let min = currentPoint.distance(stk[0]);

我建议您编写一个util函数来计算两个点之间的距离,并将两个点作为参数传递。这将是一种更清洁的方法。

,

distance内将this函数绑定到constructor

class point {
    constructor(x,id) {
        this.x = x;
        this.y = y;
        this.part = document.createElement("div");
        this.part.className = name;
        this.part.id = id;
        // bind distance method
        this.distance = this.distance.bind(this);
    }

    distance(cmp) {

        return Math.sqrt(Math.pow(cmp.x - this.x,2) + Math.pow(cmp.y - this.y,2));

    }
}
,

错误的名称是“ TypeError”。那不仅是为了娱乐。 search_min_distance中可能存在的问题:

  1. stk未定义或其长度为0
  2. stk不是点数组(typeof point [])
  3. 点未定义或不是点(typeof点) 确定的问题:
  4. point.id未定义,仅在point.part
if (stk[i].id = current.id)

 if (stk[i].part.id = current.part.id)

您的代码只是错误。

,

最后,所有这些都是一个简单的疏忽大意。我将dom用作阵列,并在应该有相等的位置进行了分配。.谢谢大家。

  if (stk[i].id = current.id)

  if (stk[i].id == current.id)

var distId = search_min_distance(stk,cp[0]);

var distId = search_min_distance(stk,stk[cp[0].id]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。