javascript - 无法访问在 Javascript 脚本标记内的 EJS 中声明的 json 数组的项目

标签 javascript json node.js express ejs

<div>  
    var arrayContent='<%= myJsonArray %>'
 <!--myJsonArray is sent to this ejs file using the render function in
 index.js while rendering this ejs file -->
</div>
<script>
  var index=0;
  function myfunc(){
  console.log(arrayContent); /*[object Object],[object Object],[object 
                                Object],[object Object] */

  var arrContentJson= JSON.parse(arrayContent);
  console.log(arrContentJson[index]); /* Uncaught SyntaxError: Unexpected 
                                         token o in JSON at position 1 */
   }
     </script>

为什么我无法访问已解析的 Json 数组 (arrContentJson) 的内容。我怎样才能访问它?

最佳答案

看起来你想将一个数组从 ejs 传递给 <script> 中的 javascript 代码标签,为此你应该使用未转义的插值 <%- %> :

<script>

    var arrayContent= <%- JSON.stringify(myJsonArray) %>;

    var index=0;

    function myfunc(){
        console.log(arrayContent);

        var arrContentJson= JSON.parse(arrayContent);
        console.log(arrContentJson[index]);
    }

    myfunc();

</script>

关于javascript - 无法访问在 Javascript 脚本标记内的 EJS 中声明的 json 数组的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48626581/

相关文章:

javascript - 使用 Node JS 的动态 PostgreSQL 文件

json - 使用 JSONP 技术从 Geonames API 加载国家国旗

javascript - 使用 async 函数作为 EventEmitter 监听器有什么问题吗?

javascript - 滚动到 Li Javascript

javascript - jquery - 脚本中的 div 使页面无效

javascript - 如何使用 AJAX - JSON 在 JSP 中保持数据更新?

java - 找不到合适的方法来解析(java.io.InputStream)

javascript - Mongodb - 按 id 和嵌入数组值搜索

javascript - iOS Safari 在使用麦克风时降低音频播放音量

javascript - 将显示属性分配给变量