我有一个像这样的javascript对象
var student = function () {
this.id = 1;
this.Name = "Shohel";
this.Roll = "04115407";
this.Session = "03-04";
this.Subject = "CSE";
};
Run Code Online (Sandbox Code Playgroud)
我有一个像这样的javascript数组列表
var students = [];
Run Code Online (Sandbox Code Playgroud)
现在我想把学生推向学生,如下所示
students.push(new student()) //no prolem
students.push(new student[id = 3]) //Problem
Run Code Online (Sandbox Code Playgroud)
这里第二行出现异常,如何将javascript对象推送为c#add list,这是代表第二行?谢谢
你根本做不到,你可以做的虽然是接受一个配置作为你的构造函数的参数,并像这样读取它
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";
};
Run Code Online (Sandbox Code Playgroud)
并称之为这样
students.push(new student({id: 3}));
Run Code Online (Sandbox Code Playgroud)
编辑,首选
正如adeneo所指出的,如果你想摆脱||默认值的重复,你可以使用jQuery传递它们
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;
};
Run Code Online (Sandbox Code Playgroud)
使值成为函数的可变参数.例如:
var Student = function (id) {
this.id = id;
// ...
};
students.push(new Student(3));
Run Code Online (Sandbox Code Playgroud)
我建议阅读有关函数的JavaScript教程: