简体   繁体   English

javascript警报功能不会显示对象

[英]javascript alert function won't show objects

I want to see the value of obj,following code is used 我想查看obj的值,使用以下代码

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

When I use alert(obj) it just gives me [object Object]. 当我使用alert(obj)时,它只是给我[object Object]。 When I use console.log(obj) it shows the object in console correctly 当我使用console.log(obj)时,它会正确显示控制台中的对象

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. message是要在警报对话框中显示的可选文本字符串,或者是转换为字符串并显示的对象。

https://developer.mozilla.org/en-US/docs/Web/API/Window.alert 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] . 由于它将所有内容都转换为字符串,这意味着它将使用object.toString()方法返回[object Object] There are many ways to format the output (see @kennebec's answer), but you can also override its toString method. 有很多格式化输出的方法(请参阅@kennebec的答案),但是您也可以覆盖其toString方法。

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. 如果您使用的是Chrome,请按Shift + Ctrl + J或F12,然后查看控制台。

Alerts simply display either strings or variables that can be cast as strings (long, float, integer). 警报仅显示字符串或可以转换为字符串(long,float,integer)的变量。 Alert cannot display any object, including arrays nor can it display pure JSON/XML or DOM elements. Alert无法显示任何对象,包括数组,也不能显示纯JSON / XML或DOM元素。 Just be careful with backwards compatibility because console.log() will break javascript in IE8 (Windows XP). 请注意向后兼容性,因为console.log()会破坏IE8(Windows XP)中的javascript。 There are other javascript tests you can perform to test for IE8 compatibility before calling your console.log() command. 在调用console.log()命令之前,还可以执行其他一些JavaScript测试来测试IE8兼容性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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