Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 44021  / 10 Years ago, thu, november 6, 2014, 12:00:00

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!


More From » arrays

 Answers
35

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.


[#68887] Tuesday, November 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;