[英]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.