前端接收一个数组作为 [object Object]

The frontend receives an array as [object Object]

我正在用 JavaScript、express.js、ejs 和 Node.js 构建一个网站,但我只是 运行 遇到了问题。

我正在以这种方式向前端发送一个数组:

const dataToSend = [
  {
    id: "ID",
    name: "Name"
  },
  {
    id: "ID",
    name: "Name"
  }
]

res.render('configure', {
    array: dataToSend
});

并以这种方式在前端使用 ejs:

<%= array %>

如果我在前端打印数组,结果将是 [object Object] 并且我还打印出 typeof('<%= array %>') 返回字符串。

我找到了一些关于此的主题,但我找不到任何有用的东西。 我想知道这样做的正确方法是什么。谢谢

这里的问题是数组正在转换为字符串。在 JavaScript 中,对象 ({...}) 有一个 toString 方法,默认情况下 returns 字符串 [object Object]

要解决这个问题,您需要确保数组没有被转换为字符串。

在 EJS 中,您有多种标签可供选择:

Tags
<% 'Scriptlet' tag, for control-flow, no output
<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it

来源:https://ejs.co/

您可能正在寻找这个:<%- 来输出 JSON.stringify 数组。

<%- JSON.stringify(array) %>