从数据文件导入数组

Import from data file into array

本文关键字:数组 导入 文件 数据      更新时间:2023-09-26

下面的代码显示应该导入值从temps.txt文件,但从times数组看起来是空的,怎么了?

我只得到"楠"作为输出。

temps.txt文件如下所示:

21.5
22.3
... etc

这是我的源代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>load demo</title>
  <style>
  body {
    font-size: 16px;
    font-family: Arial;
  }
  </style>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var times = [];
 $.get('temps.txt', function(data) {
    times = data.split("'n");
  });
for (var i in times)
 {
    document.write(times[i] + "<BR />");
 }
</script>
</html>

类似这样的东西:

1) 将循环移到$.get回调中。

2) 使用数组建立字符串

3) 使用join将其附加到body元素。

$.get('temps.txt', function(data) {
  times = data.split("'n");
  var html = [];
  for (var i in times) {
    html.push(times[i] + '<br/>');
  }
  $('body').append(html.join(''));
});