我的代碼:JavaScript對象中對象的數組,不同使用的console.log
<!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
以防萬一你不知道發生了什麼變化看看對象分配的功能 我的問題是,爲什麼輸出不同。
謝謝!所以我的錯誤是誤解了變量的範圍。 – alanx0401