Skip to content
Advertisement

A Vector Class in Javascript

I’m trying to implement a vector object instantiated like below…

var a = new Vector([1,2,3]);
var b = new Vector ([2,2,2]);

…and when I do a math operation I need something like this…

a.add(b); // should return Vector([3,4,5])

…but my code below returns me just an array

function Vector(components) {
  // TODO: Finish the Vector class.
  this.arr = components;
  this.add = add;
}

function add(aa) {
  if(this.arr.length === aa.arr.length) {
    var result=[];
    for(var i=0; i<this.arr.length; i++) {
       result.push(this.arr[i]+aa.arr[i]);
    }
    return result;
  } else {
    return error;
  }
}

Please help me out here. Thank you!

Advertisement

Answer

You need to wrap up your resulting array in a new Vector object:

function Vector(components) {
  // TODO: Finish the Vector class.
  this.arr = components;
  this.add = add;
}

function add(aa) {
  if(this.arr.length === aa.arr.length) {
    var result=[];
    for(var i=0; i<this.arr.length; i++) {
       result.push(this.arr[i]+aa.arr[i]);
    }
    return new Vector(result);
  } else {
    return error;
  }
}

I should note also that you may want to do further reading on creating JavaScript objects, in the area of creating methods (such as your add method) on the prototype of the Vector object. There are many good tutorials out there.

6 People found this is helpful
Advertisement