javascript alert() 返回的结果与 console.log() 不同?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3909006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:39:31  来源:igfitidea点击:

alert() return different from console.log()?

javascriptfirebug

提问by orolo

Should I be using alert() for debugging; or is there a time to use alert() vs. console.log()?

我应该使用 alert() 进行调试吗?或者有时间使用alert() 还是console.log()?

I see that alert() and console.log() can return different results. I assumed that they were similar functions but just returned in different places.

我看到 alert() 和 console.log() 可以返回不同的结果。我认为它们是相似的功能,只是在不同的地方返回。

Back story: my boss likes to see alerts() during development but I can't get the object details in the alert (at least not easily).

背景故事:我的老板喜欢在开发过程中查看 alerts() 但我无法在 alert 中获取对象详细信息(至少不容易)。

But when I run the same request through console.log, I get the object and all of it's parameters.

但是当我通过 console.log 运行相同的请求时,我得到了对象及其所有参数。

回答by Sid_M

Since alert could be shown to users, it tends to be literal-minded (just using toString) so a developer has a lot of control over what's shown to the user. Unlike alert, console is designed for developers, and thus tends to try to interpret a call so as to provide information that a developer would find useful: e.g. "[2, 3, 4]" is a lot more useful to a developer than "[object Object]". Alert should be the same in every browser; console's behavior could vary from browser to browser (including not being supported at all, as in IE).

由于警报可以显示给用户,它往往是字面意思(仅使用 toString),因此开发人员可以对显示给用户的内容进行很多控制。与警报不同,控制台是为开发人员设计的,因此倾向于尝试解释调用以提供开发人员认为有用的信息:例如,“[2, 3, 4]”对开发人员比“ [对象对象]”。警报在每个浏览器中都应该相同;控制台的行为可能因浏览器而异(包括根本不支持,如在 IE 中)。

回答by Michelangelo Giacomelli

try alert(JSON.stringify(yourObject)); (if your browser have json.stringify....)

尝试警报(JSON.stringify(你的对象));(如果你的浏览器有 json.stringify ....)

回答by Tim Down

alert()converts the object passed to it into a string using the object's toString()method. Unlike alert(), console.log()is not limited to displaying a simple string and can allow you to interact with the object passed to it, for example letting you inspect its properties.

alert()使用对象的toString()方法将传递给它的对象转换为字符串。与alert(),console.log()不限于显示简单的字符串,并且可以允许您与传递给它的对象进行交互,例如让您检查其属性。