首页 > 解决方案 > 读取文本文件并将其保存到列表中 (JavaScript)

问题描述

我在文本文件中有一个名词列表。我想用 JavaScript 读这个,把它保存在一个变量中,然后把它分成一个字符串列表(对应于每个名词)。我需要这些名词来为实验创建刺激。这是我尝试过的,但似乎不起作用:

function readNamesfromFileandCreateList (audiostim_name){
    //read from file a list of words, save it in a list and and shuffle it (twice for good measure)
    var openedText = await fetch(audiostim_name);
    var words = openedText.split(/\r\n|\n/);
    jsPsych.randomization.shuffle(words); jsPsych.randomization.shuffle(words); 
    return words
}

我得到的错误.split()不是函数,并且我的文本文件无法访问或加载。我正在使用网络服务器。

标签: javascripttextfilereader

解决方案


Fetch 返回响应 - 您需要调用response.text()以获取可以拆分的字符串

function readNamesfromFileandCreateList (audiostim_name){
    //read from file a list of words, save it in a list and and shuffle it (twice for good measure)
    var response = await fetch(audiostim_name);
    var openedText = await response.text(); // <-- changed
    var words = openedText.split(/\r\n|\n/);
    jsPsych.randomization.shuffle(words); jsPsych.randomization.shuffle(words); 
    return words
}

推荐阅读