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

2024-01-07

我尝试过使用console.log所以我可以看到包含多个对象的数组的内容。但是我收到一条错误消息console.log不是对象等。我正在使用 jquery 1.6.2,我的数组如下所示:

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

console.log(filters);

我想做的是写出内容array(filters)到警报框(这就是我的想法console.log做了)以过滤器格式。我怎么做?


有两种可能的简单解决方案可以将数组转储为字符串。根据您使用的环境:

...现代浏览器使用 JSON:

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

…对于像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 还有两个可选参数。第三个“spaces”参数可以实现漂亮的打印:

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"
  }
 ]
}"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

console.log 显示数组对象的内容 的相关文章

随机推荐