[英]Different behavior when printing Javascript Objects in console.log
[英]Javascript objects in array of objects,are different using 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>
這是第一個有效的版本,控制台輸出如下: 可以在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>
該版本的輸出是: 您可以在https://i.stack.imgur.com/0mQFz.png中找到圖像
萬一您不知道更改了什么,請看一下分配對象的函數。我的問題是為什么輸出不同。
你不聲明變量student
的內部setStudent
功能。 因此, 變量student
是在全局對象window
上定義的 。 當您運行此方法時,您每次都使用相同的指針,從而更改相同指針的值並將相同對象重新添加到數組中。
要解決此錯誤,只需將一個student
聲明為空對象字面量{}
我的問題是為什么輸出不同
輸出之所以不同,是因為document.write
會將當前時間點的對象轉換為string
。 在console.log
,當您擴展console.log
的箭頭時,將捕獲對象的子屬性。 如果克隆的對象或使用JSON.stringify
每次轉讓后,然后console.log
GED它們,然后輸出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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.