如何将从另一个文件接收到的数组分配给另一个数组?

How can I assign an array that I received from another file to another array?

每当我从另一个文件接收到一个数组时,我所能做的就是显示整个数组。我无法显示特定元素或将其分配给另一个数组。我已经在下面发布了一些代码。

下面是我用于 运行 节点的 .js 文件。这是发送数组的那个。

var titles = [1,2,3,4];
var descriptions = [5,6,7,8];
var dates = [9,10,11,12];
var file_names = [13,14,15,16];

app.get('/home', function(req, res) {
res.render('home', { postTitles: titles, postDescriptions: descriptions, postDates: dates, postFileNames: file_names });
});

这是我的 home.handlebars 接收数组

var myTitles = {{postTitles}};
var myDescriptions = {{postDescriptions}};
var myDates = {{postDates}};
var myFileNames = {{postFileNames}};

从节点后端在 handlebars 模板中呈现数组的方法:

  1. 当要显示整个数组时,使用 #each 助手。

  2. 如果只需要显示一个数组元素,则只将该元素传递给模板(有或没有 #with 助手)。

Example:

app.get('/home', function(req, res) {

  var myArray = [1, 2, 3, 4, 5];

  res.render('home', {

    theArray: myArray[0]

  });

});
  1. 大多数情况下,AJAX 调用用于从服务器向前端动态请求数据。这是首选方式,也是所有移动和 Web 应用程序中使用的 REST API 的基础。

  2. 也可以简单地对服务器端数组进行字符串化并将其推送到 <script> 标记中:

Handlebars template:

...

<script type="text/javascript">

    var myArray = {{theArray}};

    // here use myArray to do whatever processing is needed

</script>

...

Server-side code:

app.get('/home', function(req, res) {

  var myArray = [1, 2, 3, 4, 5];

  var jsonString = JSON.stringify(myArray);

  res.render('home', {

    theArray: jsonString

  });

});

据我所知,这是最不首选的方法。但它可以完成工作。