gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:31:11 27 4
gpt4 key购买 nike

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

我在 .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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com