2

I am extremly new in javascript so please be patient.:) I have the following object

var obj= {
    x: 0,
    y: 0
};

I want to create a function that will take x,y from the user and store them to an array. So essensialy i want an array to store "obj" objects.

var arr = []; var i;

for(i=0; i<10; i++) { arr[i] = new obj(x, y); }

I am not even sure if i have started the correct way. So how can i fill my array with objects like this?

arr= [obj1, obj2, obj3, obj4];

Thank you..

0

3 Answers 3

1

Its is correct expect if u want to use the new operator use the function.

var obj = function(a,b) {
 this.x = a;
 this.y = b;
 this.Sum = function(){
     return this.x + this.y;
 };
};

var arr = [],sumarr=[]; var i;

for(i=0; i<10; i++) 
{ 
 arr[i] = new obj(i,i+1);
 sumarr[i] = arr[i].Sum();
}

For better understanding of the concept I recommend [http://zeekat.nl/articles/constructors-considered-mildly-confusing.html].

Sign up to request clarification or add additional context in comments.

2 Comments

So how will the final code look like? Will I be able to add a+b and pass the result to a second array for each object?
you want to create a another array for sum See my updated answer
1

you can do something like t http://jsfiddle.net/naeemshaikh27/y5jaduuf/1/

 var arr = []; var obj={};
    $("#addToArray").click(function(){
        obj.x= $("#x").val();
        obj.y=$("#y").val();


        arr.push(obj);


});

Comments

1
// create a constructor for our Obj
function Obj(x, y) {
    this.x = x;
    this.y = y;
}

/* fills array with those objects */

// create an array
var objs = [];

// fill the array with our Objs
for (var i = 0; i < 10; i++) {
    objs.push(new Obj(i, i));
}

// and show the result
var msg = "";
for (var i = 0; i < objs.length; i++) {
  msg += objs[i].x + ":" + objs[i].y + '\n';
}

/* now */
alert(msg);

http://cssdeck.com/labs/elm2uj00

If you're extremely new in javascript, I would advise you read good book about javascript. For example David Flanagan's: JavaScript The Definitive Guide There are many answers of the questions that you have now and will. It's best way I can suggest. Stackoverlow will not provide you much help on your current stage. That's my opinion

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.