我正在构建一个数组,该数组将托管具有学生姓名,成绩和z分数(当前值设置为null)的对象但是在加载对象时遇到问题。
该对象应如下所示:
var 000 = {
name: "John Doe",
grade: 92,
zScore: null
};
HTML:
<div id="content">
<input type="text" id="name" placeholder= "Name . . .">
<input type="text" id="grade" placeholder = "Grade . . . ">
<button id="add">Add</button>
<button id="doMath">Do Math</button>
<br>
<br>
<ul id="list"></ul>
</div>
CSS:
#name:hover,#grade:hover {
border: 1px solid #000;
}
JavaScript的:
var studentArray = [];
var oid = 001;
var studentName = $('#name').val();
var studentGrade = (parseInt($('#name').val()));
var zScore = null;
$(document).ready(function() {
$('#add').on('click', function() {
if (studentName === "" || studentGrade === "") {
return;
};
oid = {
name: studentName,
grade: studentGrade,
z: zScore
};
//check it out
console.log(oid);
//push object to array
studentArray.push(oid);
//check out array
console.log(studentArray);
//push OID up for next student and reset inputs
$('#name').val("");
$('#grade').val("");
oid++;
});
$('#doMath').on('click', function() {});
});
我做错了什么?
答案 0 :(得分:1)
通过添加到数组,您基本上忽略了对象名称。也许您可以使用父对象?
var studentObj = {};
var oid = 001;
var studentName = "evan";
var studentGrade = "a";
var zScore = null;
//push to object
studentObj[oid] = {
name: studentName,
grade: studentGrade,
z: zScore
};
//check out object
console.log(studentObj);
//push OID up for next student and reset inputs
$('#name').val("");
$('#grade').val("");
oid++;
答案 1 :(得分:1)
查看此代码,它可以帮助您每次点击时分配值:
$('#add').on('click', function() {
studentName = $('#name').val();
studentGrade = (parseInt($('#name').val()));
...
});