简体   繁体   English

NodeJs和Ejs将Arrays传递给页面

[英]NodeJs and Ejs Pass Arrays to page

I am trying to pass an array to an .ejs page, however when I try use 我试图将数组传递给.ejs页面,但是当我尝试使用时

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. nodejs文件上的Console.log运行正常,但是当我尝试使用console.log客户端时,它会搞砸。

The issue is likely with <%= data %> , rather than console.log() . 问题可能在于<%= data %> ,而不是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. 当你只是打印一个Array ,这只是.join()元素 ,在每个元素上调用.toString() And : 而且

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

To output the data so it can be consumed, you can use JSON.stringify() : 要输出数据以便可以使用它,可以使用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 : 这利用了JSON的语法基于JavaScript的synax来输出Object文字Array文字

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

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

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