我想出了如何添加甚至修改对象数组中的实例,但是如何更改插槽“每个新的Student()都会添加一个插槽”,因此从插槽0开始,最多可以达到3。而且,我将如何删除数组的实例?
var Student = function (name, address, city, state, gpa) {
this.name = name;
this.address = address;
this.city = city;
this.state = state;
this.gpa = gpa;
console.log(name, address, city, state, gpa);
};
var Student1 = [
new Student("Some Guy","Some address","some city","some state",[2.5,3.1,4.0]),
new Student("Some Guy","Some address","some city","some state",[2.5,3.1,4.0])
];
Student1.push(new Student("Some Guy","Some address","some city","some state",[2.5,3.1,4.0]));
答案 0 :(得分:0)
要删除数组中的第一个条目,您可以使用shift()
。要删除数组中的最后一个条目,您可以使用pop()
。要删除数组中的任何其他元素,可以使用splice(index,count)
,第一个参数是要删除的索引,第二个参数是1:
var Students = [
new Student("Some Guy1","Some address","some city","some state",[2.5,3.1,4.0]),
new Student("Some Guy2","Some address","some city","some state",[2.5,3.1,4.0]),
new Student("Some Guy3","Some address","some city","some state",[2.5,3.1,4.0])
];
var s2a = Students.splice(1,1); // after this line Students contains just Some Guy1 and Some Guy 3
var s3 = Students.pop(); // after this line Students contains just Some Guy1
var s1 = Students.shift(); // after this line Students is an empty array
请注意,虽然pop
和shift
会返回删除的实际元素,但splice
会返回已删除元素的数组,在您的情况下会返回一个仅包含第二个学生的数组。
您可以在MDN上找到有关阵列和上述方法的大量信息。
答案 1 :(得分:0)
你的问题不是很清楚。但我明白的是......你想从数组中删除现有的对象。如果我的理解是正确的,请尝试array.splice(index,howmany)。
示例:
var Diseases = ["Malaria", "Plague", "AIDS", "Cancer"];
Diseases.splice(2,1);
输出:["疟疾","瘟疫","癌症"];
删除数组中的元素后,以下元素会自动移动其位置。希望这就是你要找的。 p>