I have a javascript object like this
var student = function () {
this.id = 1;
this.Name = "Shohel";
this.Roll = "04115407";
this.Session = "03-04";
this.Subject = "CSE";
};
and i have a javascript array list like this
var students = [];
now i want to push student into students, this is shown below
students.push(new student()) //no prolem
students.push(new student[id = 3]) //Problem
here second line occurs exceptions, how can i push javascript object like as c# add list, which is representing second line? thanks
You simply can't, what you can do though is accept a config as a parameter to your constructor and read it like this
var student = function (config) {
config = config || {};
this.id = config.id || 1;
this.Name = config.Name || "Shohel";
this.Roll = config.Roll || "04115407";
this.Session = config.Session || "03-04";
this.Subject = config.Subject || "CSE";
};
And call it like this
students.push(new student({id: 3}));
EDIT, PREFERRED ONE
Just as adeneo pointed out if you want to get rid of the repititive ||
for default values, you can use jQuery to pass them
var student = function (config) {
var defaults = {
id: 1,
Name: "Shohel",
Roll: "04115407",
Session: "03-04",
Subject: "CSE"
};
config = $.extend(defaults, config || {});
this.id = config.id;
this.Name = config.Name;
this.Roll = config.Roll;
this.Session = config.Session;
this.Subject = config.Subject;
};
Make the values that are variable parameters of the function. For example:
var Student = function (id) {
this.id = id;
// ...
};
students.push(new Student(3));
I recommend to read a JavaScript tutorial about functions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With