脚本标签中的EJS变量/设置数组到变量成为字符串

发布于 2025-02-02 02:42:19 字数 888 浏览 0 评论 0原文

因此,我需要将变量传递给EJS文件中的脚本标签。这是问题数组(我无缘无故地将其称为var名称中的对象),我需要在脚本标签中使用。我看到它是由'<% - varname%>'完成的。 但是问题是,我想在使用它的同时从数组中删除东西,因此我需要此数组的副本。这是问题:

console.log('<%-passedUser.questionsObject%>')
console.log('<%-passedUser.questionsObject[0]%>')
arrayToUse = '<%-passedUser.questionsObject%>'
console.log(arrayToUse)
console.log(arrayToUse[0])

输出:

question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2 

question1,answer1,answer2,answer3,answer4,answer5 

question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2 

q

我尝试了json.stringify,分析,什么都没有。感谢任何帮助。

注意:我不知道为什么'&lt;% - vasseuser.questionsObject%&gt;'没有记录正确的方式,但它给出了正确的值。真正的形式是:

[[question1,answer1,answer2,answer3,answer4,answer5],[q2,answer1,answer2]]

So i needed to pass a variable to the script tag in the ejs file. it's question array (i called it object in the var name for no reason), that i need to work with in the script tag. i saw that it's done by '<%-varname%>'.
But the thing is, i want to remove stuff from the array while working with it, so i need a copy of this array. And here is the problem:

console.log('<%-passedUser.questionsObject%>')
console.log('<%-passedUser.questionsObject[0]%>')
arrayToUse = '<%-passedUser.questionsObject%>'
console.log(arrayToUse)
console.log(arrayToUse[0])

Output:

question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2 

question1,answer1,answer2,answer3,answer4,answer5 

question1,answer1,answer2,answer3,answer4,answer5,q2,answer1,answer2 

q

I tried JSON.stringify, parse, nothing works. i'd appreciate any help.

Note: i don't know why '<%-passedUser.questionsObject%>' isn't logging the correct way, but it's giving correct values. It's true form is :

[[question1,answer1,answer2,answer3,answer4,answer5],[q2,answer1,answer2]]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

相权↑美人 2025-02-09 02:42:19

您必须同时使用JSON Parse和JSON Stringify,

arrayToUse = JSON.parse('<%- JSON.stringify(passedUser.questionsObject)%>')

轻松地使用该数组或执行该数组

const [questions,answers] = arrayToUse

您可以在发送给客户端之前

<% const [questions,answers] = passedUser.questionsObject %>

<script>
  const  arrayToUse = JSON.parse('<%- JSON.stringify(questions)%>')
</script>

you have to use both json parse and json stringify

arrayToUse = JSON.parse('<%- JSON.stringify(passedUser.questionsObject)%>')

later you can easily split the array using

const [questions,answers] = arrayToUse

or do it before sending it to the client

<% const [questions,answers] = passedUser.questionsObject %>

<script>
  const  arrayToUse = JSON.parse('<%- JSON.stringify(questions)%>')
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文