NodeJs and Ejs Pass Arrays to page

删除回忆录丶 提交于 2021-01-20 18:17:07

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/16509733/nodejs-and-ejs-pass-arrays-to-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!