javascript - 在 HTML 文件中使用 Javascript 逐行读取文本文件并存储在变量中

标签 javascript html arrays file-io

本质上,我需要创建一个数组的数组。

我在 .HTML 文件中使用 Javascript。我正在读取 .txt 文件

我们将第一个数组称为“警报”,然后将其中的每个数组称为“事件”。

每个事件都具有与其关联的三个值:ID 号、纬度值和经度值。

如果我将这些值放入一个文本文件中,并且每个值都位于单独的行中,那么我应该使用什么函数/如何读取每个值,然后将它们分配给要存储在事件数组中的变量?

<script type="text/javascript">

        //open text file
        $f = fopen("LatLngTest.txt", "r");
        //read line by line: 1st line=ID, 2nd line=LAT, 3rd line=LNG

        //store in ID, LAT, LNG variables

        //close text file
        fclose($f);
        //create incident array and save ID, LAT, LNG as one incident
        var incident = new Array (ID, LAT, LNG);

        //create array of alerts
        var alerts = new Array();
        //if statement to check length of array 

            //and add this incident to the end
            //alerts[i] = incident;
    </script>

最佳答案

您需要在将文本发送到服务器之前为页面提供文本,或者使用 AJAX。我假设对您来说最简单的方法就是将其转储到页面上:

<script>
  (function(){
    <?php echo "var fileContent = '" . file_get_contents("LatLngTest.txt") . "'," ; ?>
    alerts = fileContent.split("\n").map(function(lineItem){
       // Assuming each line is csv: ID,LAT,LNG 
       // and that there are no commas in the values
       var field = lineItem.split(",");
       return {ID: field[0], LAT: field[1], LNG: fields[2]};
    });

    // now alerts looks like this: [{ID: ..., LAT: ..., LNG: ...}, {...}];

  })();
</script>

关于javascript - 在 HTML 文件中使用 Javascript 逐行读取文本文件并存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106245/

相关文章:

javascript - AngularJS 在指令中操作父级的 DOM

javascript - 以不同的分辨率显示图像

javascript - object.style ['background'] 在 Mozilla 中不起作用

javascript - 类型错误 : undefined is not an object (evaluating 'this.__reactAutoBindMap' )

javascript - 故事书中的垂直滚动不准确

c# - 使用 Javascript 确定单击了哪个 ASP.NET 按钮

javascript - 从本地存储 JavaScript 中的对象数组中删除一个对象

html - 居中对齐水平 div

使用数组进行 C 编程读写

arrays - 在 numpy 中的给定日期周围生成 -1/+1 天