简体   繁体   English

逐行读取本地文本标题,将行存储在数组中

[英]Read local text title line-by-line, store lines in an array

I have a local text file wordsEn.txt that is all words in the dictionary (lowercased): 我有一个本地文本文件wordsEn.txt ,它是字典中的所有单词(小写):

a
aah
aahed
aahing
aahs
aardvark
[etcetera]

On page load, I would like those to be placed into an array: 在页面加载时,我希望将它们放置到数组中:

words = ["a", "aah", "aahed", "aaching", "aahs", "aardvark", ...];

Here's the function I made to return the response code when trying to read the text file: 这是我尝试读取文本文件时返回响应代码的函数:

    function get_words()
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("POST", "wordsEn.txt", true);
        rawFile.onreadystatechange = function ()
        {
            if (rawFile.readyState === 4)
            {
                if (rawFile.status === 200 || rawFile.status == 0)
                {
                    return rawFile.responseText;
                }
            }

        }
        rawFile.send(null);
    }

I was trying to copy the procedure here: Javascript - read local text file 我试图在此处复制该过程: Javascript-读取本地文本文件

(I confess that I copied it without really understanding what it does.) (我承认我是在没有真正理解它的情况下复制它的。)

Apparently it's not working, because 显然它不起作用,因为

    var resp = get_words(); 
    document.getElementById("spresdiv").innerHTML += "<p>" + resp + "</p>";

writes undefined inside the spresdiv div. spresdiv div中写入undefined Any idea why this is and how I can fix it? 知道为什么会这样以及如何解决吗?

On a related note, does anyone know if JavaScript arrays are implemented with a tree or any other type of fast-lookup? 与此相关的是,有谁知道JavaScript数组是用树还是任何其他类型的快速查找实现的? Does indexOf(...) use a linear search? indexOf(...)是否使用线性搜索?

Ajax is Asynchronous. Ajax是异步的。 you can't return the responseText from get_words . 您不能从get_words返回responseText You should instead use callbacks. 您应该改为使用回调。

function get_words(callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("POST", "wordsEn.txt", true);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                callback(rawFile.responseText);
            }
        }

    }
    rawFile.send(null);
}

get_words(function (resp) {
    document.getElementById("spresdiv").innerHTML += "<p>" + resp + "</p>";
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM