console.log showing contents of array object

后端 未结 7 1829
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 16:02

I have tried using console.log so I can see the content of my array that contains multiple objects. However I get an error saying console.log is not an

7条回答
  •  臣服心动
    2021-01-30 16:52

    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.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()

    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. 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"
      }
     ]
    }"
    

提交回复
热议问题