为什么在我的类中执行方法时会得到 NaN,而在单独执行时却不会?

我正在尝试学习编码列车的 Daniel Shiffman 介绍的“自主转向行为”课程。 See Video Tutorials Here

这些课程是使用 P5.js 库提供的,但我想使用纯 JavaScript 继续学习。

我已经创建了自己的 vector 类,以及一个表示受力控制的对象的 vehicle 类。

当我单独运行 vector 类方法时,addsubtract 方法按预期工作。但是,当我尝试在 this.velocity.add(desiredVelocity) 类中执行 vehicle 时,velocity 向量返回 'NaN'

独立运行的代码(按预期工作)是

let v1 = new Vector(10,10)
let v2 = new Vector(20,30)
console.log(v1.add(v2)) // Outputs Vector(30,40)

我忽略或不知道导致 this.velocity.add(desiredVelocity) 返回 NaN 的原因是什么?

class Vector{
    constructor(x,y){
        this.x = x == undefined ? 0 : x,this.y = y == undefined ? 0 : y
    }

    magnitude(){
        return Math.sqrt(this.x * this.x + this.y * this.y); 
    }

    setMagnitude(newMagnitude){
        this.x = this.x * newMagnitude / this.magnitude();
        this.y = this.y * newMagnitude / this.magnitude();
        return new Vector(this.x,this.y);
    }
    
    add(vector){
        this.x += vector.x;
        this.y += vector.y;
        return new Vector(this.x,this.y)
    }

    static subtract(vector1,vector2){
        return new Vector(vector1.x - vector2.x,vector1.y - vector2.y);
    }
}



class Vehicle {
    constructor(){
        this.position = new Vector();
        this.velocity = new Vector();
        this.maxSpeed = 10;
    }

    seek(target) {
        let desiredVelocity = Vector.subtract(target.position,this.position);
        desiredVelocity.setMagnitude(this.maxSpeed);
        this.velocity.add(desiredVelocity)
        console.log('new velocity',this.velocity) // Returns NaN
    }

}

class Target{
    constructor(){
        this.position = new Vector();
    }
}


const vehicle = new Vehicle();
const target = new Target()
vehicle.seek(target)

zhanghaowl 回答:为什么在我的类中执行方法时会得到 NaN,而在单独执行时却不会?

Vector#setMagnitude 中,您除以 Vector#magnitude 返回的值,可以是 0。当 newMagnitude 也是 0 时,您会得到 0 / 0,结果为 NaN

本文链接:https://www.f2er.com/2644.html

大家都在问