简体   繁体   中英

NodeJs and Ejs Pass Arrays to page

I am trying to pass an array to an .ejs page, however when I try use

var test ="<%= data %>";
console.log(test);

I get the output

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object

Console.log on the nodejs file works fine, but its when I try console.log client side it messes up.

The issue is likely with <%= data %> , rather than console.log() . If you check the result client-side, you'll probably see:

var test ="[object Object],[object Object],[object Object],...";

When you simply print an Array , this will just .join() the elements , calling .toString() on each. And :

new Object().toString() === "[object Object]"

To output the data so it can be consumed, you can use JSON.stringify() :

var test = <%- JSON.stringify(data) %>;

This takes advantage of JSON's syntax being based on JavaScript's synax to output an Array literal of Object literals :

var test = [{"prop":"value"},...];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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