gpt4 book ai didi

javascript对象创建

转载 作者:搜寻专家 更新时间:2023-11-01 04:50:20 25 4
gpt4 key购买 nike

我有一个像这样的 javascript 对象

 var student = function () {
this.id = 1;
this.Name = "Shohel";
this.Roll = "04115407";
this.Session = "03-04";
this.Subject = "CSE";
};

我有一个像这样的 javascript 数组列表

var students = [];

现在我想把学生推给学生,如下图所示

students.push(new student())  //no prolem

students.push(new student[id = 3]) //Problem

此处第二行出现异常,我如何推送 javascript 对象,如 c# 添加列表,代表第二行?谢谢

最佳答案

你根本做不到,你可以做的是接受一个配置作为你的构造函数的参数并像这样读取它

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";
};

然后这样调用它

students.push(new student({id: 3}));

编辑,首选一个

正如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;
};

关于javascript对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com