MavrosGatos
MavrosGatos

Reputation: 529

Create a javascript object and then fill an array through a for loop

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..

Upvotes: 2

Views: 1755

Answers (3)

Mark Zucchini
Mark Zucchini

Reputation: 925

// 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

Upvotes: 1

Krishjs
Krishjs

Reputation: 368

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].

Upvotes: 1

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

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);


});

Upvotes: 1

Related Questions