我的代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<script>
var students = [];
var student = {};
var scores = [];
var final = [];
function setStudent(name , score) {
student = {"Name": name, "Score": score};
//student.Name = name;
//student.Score = score;
document.write(student.Name + " scored " + student.Score + ".<br>");
final.push(student);
return student;
}
for (var i=0; i<4; i++) {
students.push(prompt("Please Enter student name"));
}
for (var i=0; i<4; i++) {
scores.push(prompt("Please Enter "+ students[i] +"'s score" ))
}
for (var i=0; i<4; i++) {
setStudent(students[i],scores[i]);
}
console.log(final);
</script>
</body>
</html>
这是第一个有效的版本,控制台输出如下所示: Image can be found at http://i.imgur.com/HnEHX5J.png
虽然第二个版本是:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<script>
var students = [];
var student = {};
var scores = [];
var final = [];
function setStudent(name , score) {
//student = {"Name": name, "Score": score};
student.Name = name;
student.Score = score;
document.write(student.Name + " scored " + student.Score + ".<br>");
final.push(student);
return student;
}
for (var i=0; i<4; i++) {
students.push(prompt("Please Enter student name"));
}
for (var i=0; i<4; i++) {
scores.push(prompt("Please Enter "+ students[i] +"'s score" ))
}
for (var i=0; i<4; i++) {
setStudent(students[i],scores[i]);
}
console.log(final);
</script>
</body>
</html>
此版本的输出是: You can find image at https://i.stack.imgur.com/0mQFz.png
万一你不知道改变了什么,看看分配对象的功能 我的问题是为什么输出不同。
答案 0 :(得分:0)
您未在student
函数中声明变量setStudent
。因此,the variable student
is defined on the global object window
。运行此方法时,每次都使用相同的指针,从而更改同一指针的值并将相同的对象重新添加到数组中。
要解决此错误,只需将student
声明为空对象文字{}
我的问题是为什么输出不同
输出不同的原因是document.write
会将当前点的对象及时转换为string
。在console.log
中,在console.log
中展开箭头时,抓取对象的子属性。如果您在每次分配后克隆了对象或使用了JSON.stringify
,然后console.log
使用了console.log
,那么var students = [];
var student = {};
var scores = [];
var final = [];
function setStudent(name, score) {
//student = {"Name": name, "Score": score};
// ERROR HERE
// you're not declaring the variable `student` therefore, the variable `student` is defined on the global object `window`. When you run this method, you're using the same pointer every time and thus changing the pointer and readding it to the array.
var student = {}; // this is the fix
student.Name = name;
student.Score = score;
document.write(student.Name + " scored " + student.Score + ".<br>");
final.push(student);
return student;
}
for (var i = 0; i < 4; i++) {
students.push(prompt("Please Enter student name"));
}
for (var i = 0; i < 4; i++) {
scores.push(prompt("Please Enter " + students[i] + "'s score"))
}
for (var i = 0; i < 4; i++) {
setStudent(students[i], scores[i]);
}
console.log(final);
的输出将符合预期。
{{1}}&#13;