简体   繁体   中英

javascript alert function won't show objects

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

   alert(JSON.stringify(obj))

返回属性名称及其对象值的字符串。

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); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM