简体   繁体   English

console.log 显示数组对象的内容

[英]console.log showing contents of array object

I have tried using console.log so I can see the content of my array that contains multiple objects.我尝试使用console.log以便我可以看到包含多个对象的数组的内容。 However I get an error saying console.log is not an object etc. I'm using jquery 1.6.2 and my array is like this:但是我收到一条错误消息,说console.log不是对象等。我使用的是 jquery 1.6.2,我的数组是这样的:

filters = {dvals:[{'brand':'1', 'count':'1'},
                  {'brand':'2', 'count':'2'}, 
                  {'brand':'3', 'count':'3'}]}

console.log(filters);

What I want to to do is write out the contents of array(filters) to an alert box (that's what I thought console.log did) in the filters format.我想要做的是将array(filters)的内容以过滤器格式写出到警报框(这就是我认为console.log所做的)。 How do I do that?我怎么做?

there are two potential simple solutions to dumping an array as string.将数组转储为字符串有两种潜在的简单解决方案。 Depending on the environment you're using:根据您使用的环境:

…with modern browsers use JSON: …现代浏览器使用 JSON:

JSON.stringify(filters);
// returns this
"{"dvals":[{"brand":"1","count":"1"},{"brand":"2","count":"2"},{"brand":"3","count":"3"}]}"

…with something like node.js you can use console.info() ……像 node.js 这样的东西,你可以使用 console.info()

console.info(filters);
// will output:
{ dvals: 
[ { brand: '1', count: '1' },
  { brand: '2', count: '2' },
  { brand: '3', count: '3' } ] }

Edit:编辑:

JSON.stringify comes with two more optional parameters. JSON.stringify 带有另外两个可选参数。 The third "spaces" parameter enables pretty printing:第三个“空格”参数启用漂亮的打印:

JSON.stringify(
                obj,      // the object to stringify
                replacer, // a function or array transforming the result
                spaces    // prettyprint indentation spaces
              )

example:例子:

JSON.stringify(filters, null, "  ");
// returns this
"{
 "dvals": [
  {
   "brand": "1",
   "count": "1"
  },
  {
   "brand": "2",
   "count": "2"
  },
  {
   "brand": "3",
   "count": "3"
  }
 ]
}"

It's simple to print an object to console in Javascript.在 Javascript 中将对象打印到控制台很简单。 Just use the following syntax:只需使用以下语法:

console.log( object );

or要么

console.log('object: %O', object );

A relatively unknown method is following which prints an object or array to the console as table:下面是一个相对未知的方法,它将对象或数组作为表格打印到控制台:

console.table( object );控制台表(对象);

I think it is important to say that this kind of logging statement only works inside a browser environment.我认为重要的是要说这种日志语句仅在浏览器环境中有效。 I used this with Google Chrome.我在谷歌浏览器中使用了它。 You can watch the output of your console.log calls inside the Developer Console: Open it by right click on any element in the webpage and select 'Inspect'.您可以在开发人员控制台中查看 console.log 调用的输出:通过右键单击网页中的任何元素并选择“检查”打开它。 Select tab 'Console'.选择选项卡“控制台”。

console.log does not produce any message box. console.log不会产生任何消息框。 I don't think it is available in any version of IE (nor Firefox) without the addition of firebug or some equivalent.我不认为它在任何版本的 IE(或 Firefox)中都不可用,除非添加 firebug 或一些等效的东西。

It is however available in Safari and Chrome.但是它在 Safari 和 Chrome 中可用。 Since you mention Chrome I'll use that for my example.既然你提到了 Chrome,我将在我的例子中使用它。

You'll need to open your window and its developer window counterpart.您需要打开您的窗口及其对应的开发人员窗口。 you can do this by right clicking any element on the page and selecting "Inspect element".您可以通过右键单击页面上的任何元素并选择“检查元素”来执行此操作。 your window will be divided in two parts, the developer part being the bottom.您的窗口将分为两部分,开发人员部分位于底部。 in the division between the two parts is a bar with buttons and the rightmost button there is labeled "console".在两部分之间的分界处是一个带按钮的栏,最右边的按钮标有“控制台”。 You'll need to click that to switch to the console tab.您需要单击它才能切换到控制台选项卡。 Press F12 for developer tools in most browsers on Windows, command + shift + I on macOS.在 Windows 上的大多数浏览器中按 F12 获取开发人员工具,在 macOS 上按 command + shift + I。

Once there, you will be able to interact with whatever page is loaded on top through javascript from that console, and any messages you console.log will be displayed there.在那里,您将能够通过来自该控制台的 javascript 与加载在顶部的任何页面进行交互,并且您的console.log任何消息都将显示在那里。

The console object is available in Internet Explorer 8 or newer, but only if you open the Developer Tools window by pressing F12 or via the menu. console对象在Internet Explorer 8或更高版本中可用,但前提是您按F12或通过菜单打开开发人员工具窗口。

It stays available even if you close the Developer Tools window again until you close your IE.即使您再次关闭“开发者工具”窗口,它仍然可用,直到您关闭 IE。

Chorme and Opera always have an available console , at least in the current versions. Chorme 和 Opera 总是有一个可用的console ,至少在当前版本中是这样。 Firefox has a console when using Firebug, but it may also provide one without Firebug. Firefox 在使用 Firebug 时有一个console ,但它也可能提供一个没有 Firebug 的console

In any case it is a save approach to make the use of console output optional.在任何情况下,使用console输出都是可选的保存方法。 Here are some examples on how to do that:以下是有关如何执行此操作的一些示例:

if (console) {
    console.log('Hello World!');
}

if (console) console.debug('value of someVar: ' + someVar);

I warmly recommend this snippet to ensure, accidentally left code pieces don't fail on clients browsers:我热烈推荐这个片段,以确保意外留下的代码片段不会在客户端浏览器上失败:

/* neutralize absence of firebug */
if ((typeof console) !== 'object' || (typeof console.info) !== 'function') {
    window.console = {};
    window.console.info = window.console.log = window.console.warn = function(msg) {};
    window.console.trace = window.console.error = window.console.assert = function(msg) {};
}

rather than defining an empty function, this snippet is also a good starting point for rolling your own console surrogate if needed, ie dumping those infos into a .debug Container, show alerts (could get plenty) or such...与定义一个空函数不同,此代码段也是在需要时滚动您自己的控制台代理的一个很好的起点,即将这些信息转储到 .debug 容器中,显示警报(可能会得到很多)等等......

If you do use firefox+firebug, console.dir() is best for dumping array output, see here .如果您确实使用 firefox+firebug,则console.dir()最适合转储数组输出,请参见此处

Seems like Firebug or whatever Debugger you are using, is not initialized properly.似乎 Firebug 或您使用的任何调试器未正确初始化。 Are you sure Firebug is fully initialized when you try to access the console.log()-method?当您尝试访问 console.log() 方法时,您确定 Firebug 已完全初始化吗? Check the Console-Tab (if it's set to activated).检查控制台选项卡(如果它设置为激活)。

Another possibility could be, that you overwrite the console-Object yourself anywhere in the code.另一种可能性是,您自己在代码中的任何地方覆盖了控制台对象。

Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. Json 代表 JavaScript Object Notation,实际上所有 json 都是 javascript 对象,因此您的数组已经是 json 形式。 To write it out in a div you could do a bunch of things one of the easiest I think would be:要在 div 中写出来,你可以做很多事情,我认为最简单的事情之一是:

 objectDiv.innerHTML = filter;

where objectDiv is the div you want selected from the DOM using jquery.其中 objectDiv 是您要使用 jquery 从 DOM 中选择的 div。 If you wanted to list parts of the array out you could access them since it is a javascript object like so:如果你想列出数组的一部分,你可以访问它们,因为它是一个像这样的 javascript 对象:

 objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.

edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString() function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();编辑:任何你想成为一个字符串但目前不是的(这是罕见的 javascript 将几乎所有的东西都当作一个字符串)只需使用内置的toString()函数。所以如果你需要,上面的行将是filter.dvals.valueToDisplay.toString();

second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.澄清的第二个编辑:这个答案是对 OP 的评论的回应,而不是完全回应他的原始问题。

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

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