使用Java脚本将文本文件读取到数组中 [英] Read text file using java script into an array

查看:128
本文介绍了使用Java脚本将文本文件读取到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好专家,

我想使用Java脚本读取文本文件.我是按照以下方式做的.

Hello expert,

I want to read a text file using java script. I did it in following manner..

<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>

<body>
<script language="JavaScript" type="text/javascript">
<!--
var srcFrame;
//External content into a layer
function loadOuter(doc) {
 srcFrame = document.getElementById("hiddenContent");
 srcFrame.src = doc;
 // workaround for missing onLoad event in IFRAME for NN6
 if (!srcFrame.onload) {
  setTimeout("transferHTML()", 1000)
 }
}

function transferHTML(){
 srcContent='';
 if (srcFrame.contentDocument){
  srcContent=srcFrame.contentDocument.getElementsByTagName("BODY")[0].innerHTML;
 }
 else if (srcFrame.contentWindow){
  srcContent=srcFrame.contentWindow.document.body.innerHTML;
 }
 document.getElementById("outerDisplay").innerHTML = srcContent
}



//-->
</script>

<INPUT TYPE="button" VALUE="input.txt" onClick="loadOuter('input.txt')" >
<div id="outerDisplay"></div>
<iframe  id="hiddenContent" width="200" height="200" style="position:absolute;visibility:hidden;" ></iframe>

</body>
</html>



上面的代码能够立即读取文本文件,并可以将其显示为html.

现在假设我在同一文件中有CSV字符串,并且如果我需要将其读取为二维数组,那么我应该在这里做什么?

链接 http://stackoverflow.com/问题/6861180/how-can-you-read-a-file-line-by-line-in-javascript [



Above code is able to read the text file at once and can show it in html.

Now suppose I have CSV strings in that same file, and If i need to read it into two dimensional array then what should I do here?

The link http://stackoverflow.com/questions/6861180/how-can-you-read-a-file-line-by-line-in-javascript[^] explains doing the same by using xmlHttpRequest object. But If I refere it, I could not able to read file content rather I don''t know how to implement the given function in my html.

Any help please???

推荐答案

CSV [ ^ ]通常是逗号(或TAB)分隔文字格式.
因此,您可以做的是拆分 [添加 [
CSV[^] is usually a comma (or TAB)-separated text format.
So what you can do is split[^] the text string using the new-line character first, this will give you an array of lines.
Then for each of these lines, split the line using the comma character, giving you an array of tokens for each line.
You can add[^] each of these token arrays to a new array giving you your desired 2D array

I hope this helps.


这篇关于使用Java脚本将文本文件读取到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆