点击时创建一个新对象

3

你好, 我的问题可能有点“新手”,因为我是新手! 我有一个像这样的对象:

var person = {
   firstName: null, 
   lastName: null, 
   age: null, 
   eyeColor: null
};

当我点击“添加”按钮以添加新人(新对象)时,我希望有类似以下的内容...
$("p").click(function(){
    var newPerson = new Person("John", "Doe", "50", "blue");
    console.log("A new person has been created!");
});

但这种情况只适用于一个对象...我该如何创建许多具有不同参数,特别是不同对象名称(var newPerson)的新人物? 我知道可以使用带参数的函数,但对象的名称仍然相同,因此对象会被新对象替换... 我希望我说得清楚...或者至少有人能明白我的意思!谢谢! :)

使用一个数组来存储对象。 - Nenad Vracar
一个数组应该能够工作,但是数组的索引应该是什么? - EricF
每次我点击按钮时,x的值没有改变... 就像这样: arr[x] = new Person(param1, param2, param3, param4); - EricF
2个回答

4
当你使用 var 关键字并使用相同的标签时,它将切换你所引用的对象,因此真正的问题是找到存储People类实例的位置,而不是创建不同的变量名。像这样的东西可能会起作用:
var people = [];

$("p").click(function(){
    var newPerson = new Person("John", "Doe", "50", "blue");
    people.push(newPerson);
    console.log("A new person has been created!");
});

这样,您可以通过在people数组中存储的索引来引用不同的人。 console.log(people[0]) //-> {firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"} 希望这有所帮助!

1
这正是我所需要的!!谢谢!:) - EricF
没问题!√√√ - kqcef

-1

我想这会对你的问题有所帮助:

HTML部分:

<form method="POST" id="form">
<input id="name" placeholder="First name"></input><br>
<input id="lname" placeholder="Last name"></input><br>
<input id="age" placeholder="Age"></input><br>
<input id="eye" placeholder="Eye Color"></input><br>
<button type="submit" id="btn">CREATE</button>
</form>

JS部分:

function person(f_name, l_name, age, eye_c) {
  this.fname = f_name;
  this.lname = l_name;
  this.age = age;
  this.eyec = eye_c; 
}  // Defining the object, consider it like a object template.
person.prototype.notif = function () {
    alert("The user with name " + this.fname + " logged in!");
    }  // Here is a function added outside the object, does not need to be done this way...It pops an alert box.

var id = 0; // ...so we can track the id/number of submits.
var list = []; // Here we will put all the entries, objects.
document.getElementById("form").onsubmit = function(event) {
  event.preventDefault();
  var name_value = document.getElementById("name").value; // Taking the value from the input field.
  var lname_value = document.getElementById("lname").value; // Taking the value from the input field.
  var age_value = document.getElementById("age").value; // Taking the value from the input field.
  var eye_value = document.getElementById("eye").value; // Taking the value from the input field.
  list[id] = new person(name_value, lname_value, age_value, eye_value); // Making the new object of name list with an ID ( list0, list1... )
  list[id].notif();  // Giving the notification...
  id++;  // Increasing the ID afther every submit, so we can track the list.
  console.log(list);
};  // Creating the new object (could be new acc for example), with the entered parameters.

你能提供一份解释来辅助这段代码吗? - jhpratt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接