0

For some reason, printing an array of objects in console.log() doesn't print each object correctly.

When I loop through the array for each individual object and print its property I am interested in, it differs from the object being printed in the array. I performed this check before and after I print the array of objects with the check having matching property values while sometimes differing with the array.

What could be some reasons for this? I am happy to give more details but I'm not sure what is relevant to this problem.

for(let i = 0; i < activeMonsters.length; i++) {
    console.log("Before: " + i + "|" + activeMonsters[i].xPos);
    // console.log(activeMonsters[i]);
}
console.log(activeMonsters);
for(let i = 0; i < activeMonsters.length; i++) {
    // console.log(activeMonsters[i]);
    console.log(i + "|" + activeMonsters[i].xPos);
}
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
Hyrial
  • 1,728
  • 3
  • 15
  • 27

1 Answers1

2

It is not a bug, console.log() works as per design. If I understand correctly you want to see Objects in details for that use:

Option 1:

console.dir() to print browserable Object in chrome console.

For more information please check here : https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

Option 2:

console.log(JSON.stringify());

This should also give you browserable Object.

Community
  • 1
  • 1
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
  • So `console.log()` is only designed to work sometimes when printing objects? – Hyrial Jul 17 '18 at 04:16
  • @HenryZhang I mentioned console.dir() is to print object with its properties. Your question is too wague and difficult to understand. What do you mean by **sometimes differing with the array**. Add proper examples in question. – Vikasdeep Singh Jul 17 '18 at 04:27
  • I'm just wondering why console.log() is inconsistent when printing objects. In the above example, xPos is an integer and the for loops sometimes print a different number than the xPos property of objects in the activeMonsters array. – Hyrial Jul 17 '18 at 04:40
  • Again, Information is not enough. What out are you getting on console? Better to add screenshots of both outputs. Maybe that is happening due to different input i.e. `activeMonsters` has different value. – Vikasdeep Singh Jul 17 '18 at 04:45