javascript alert function won't show objects

2019-09-07 05:48发布

问题:

I want to see the value of obj,following code is used

var obj = { 
            x: 'abc',
            y: 2,
            z: 3 
                   };

When I use alert(obj) it just gives me [object Object]. When I use console.log(obj) it shows the object in console correctly

why this alert function cant shows the object as it is...???

is there anymore data types that alert function cant show correcly

回答1:

Alert's message parameter:

message is an optional string of text you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed.

https://developer.mozilla.org/en-US/docs/Web/API/Window.alert

Since it convert everything to strings, it means it uses object.toString() method which returns [object Object]. There are many ways to format the output (see @kennebec's answer), but you can also override its toString method.

Here's a simple example of overriding it into a nicely formatted string:

var obj = {
  x: 'abc',
  y: 2,
  z: 3
};

Object.prototype.toString = function() {
  var output = "";
  for (var i in this) {
    output += i + ": " + this[i] + "\n";
  }
  return output;
}

alert(obj);



回答2:

   alert(JSON.stringify(obj))

returns a string of the property names and their values of an object.



回答3:

Use

console.log(obj)

to display objects in a modern browser. If you're using Chrome, press Shift+Ctrl+J or F12 to then see the console.

Alerts simply display either strings or variables that can be cast as strings (long, float, integer). Alert cannot display any object, including arrays nor can it display pure JSON/XML or DOM elements. Just be careful with backwards compatibility because console.log() will break javascript in IE8 (Windows XP). There are other javascript tests you can perform to test for IE8 compatibility before calling your console.log() command.