javascript中定义一维数组,如何从TXT文件中为其赋值?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript中定义一维数组,如何从TXT文件中为其赋值?相关的知识,希望对你有一定的参考价值。

通常,在JS中定义一维数据可以这样写:
var name_list = new Array("张三","李四","王二","刘五","小花");
问题:
已经建立了一个TXT文件,格式为"张三","李四","王二","刘五","小花",或每个人名一行,即如下格式:
张三
李四
王二
刘五
小花
请问:如何上面JS函数new Array括号里的内容,自动提取TXT文件来填充呢?
不胜感激!跪求!

其实只要读取成字符串用 split("\\n") 切割就可以了。

因为你没有说哪个平台,那就拿浏览器举个例子:

<!DOCTYPE html>
<html>
<body>
  <input type="file" id="input">
  <script>
  (function()
    var input = document.querySelector('#input');

    input.addEventListener('change', function(e)
      handFile(e.target.files[0]);
    );

    function handFile(file)

      var reader = new FileReader();

      reader.onload = function(e)
        console.log(e.target.result.split("\\n"));
      ;

      reader.readAsText(file);
    
  )();
  </script>
</body>
</html>

浏览器需要<input>标签读取文件,node.js 的话可以从命令行参数 process.argv 来传入文本

想要在脚本里面读取文本文件可以用 fs 模块。

参考技术A 在win下,纯jscript脚本可以用FSO进行文件读写,
比如,在一个test.js文件中写上
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.OpenTextFile("c:\\\\文件名.txt", ForReading, false); //读文件
var s = f.ReadLine();读一行

如果要在浏览器中读写,需要大大降低自定义安全级别,允许使用本地ActiveX对象。
通常这么做是非常危险的。。

将数组从平面一维转换为树,如 javascript/lodash

【中文标题】将数组从平面一维转换为树,如 javascript/lodash【英文标题】:transform an array from a flat 1 dimensional to a tree like in javascript/lodash 【发布时间】:2020-08-19 00:04:36 【问题描述】:

我无法将以下数组 data1 转换为看起来像 data2:我尝试使用 lodash 但它有点奇怪 _gropuby 给了我一个对象数组。我应该在数组内部循环...为此创建一个自定义函数。或者 lodash 中是否有一个技巧来简化这一点。谢谢 /************************************************* *************************************************

let data1 = [
    KlasCode: "AA",
    LESDatum: "06/02/2017",
    LESID: "1",
    ModuleID: "1061",
    ParticipationLetterCode: "Y"
  , 
    KlasCode: "AA",
    LESDatum: "07/02/2017",
    LESID: "2",
    ModuleID: "1061",
    ParticipationLetterCode: "X",
  ,
  
    KlasCode: "AA",
    LESDatum: "13/02/2017",
    LESID: "3",
    ModuleID: "1062",
    ParticipationLetterCode: "Z"
  ,
  
    KlasCode: "BB",
    LESDatum: "16/02/2017",
    LESID: "4",
    ModuleID: "1063",
    ParticipationLetterCode: "X"
  
]

//The output should be like a tree array system, something more organized such as the following code :
let data2 = [
    KlasCode: "AA",
    Modules: [
      
      ModuleID: "1061",
      Participation: [
          ParticipationLetterCode: "Y",
          LESDatum: "06/02/2017",
          LESID: "1"
        ,
        
          ParticipationLetterCode: "X",
          LESDatum: "07/02/2017",
          LESID: "2"
        
      ,
       
          ModuleID: "1062",
          Participation:[
          ParticipationLetterCode: "Z",
          LESDatum: "13/02/2017",
          LESID: "3"
                         ]
        

    ]
  ,
  
    KlasCode: "BB",
    Modules: [
      ModuleID: "1063",
      Participation: [
        ParticipationLetterCode: "x",
        LESDatum: "6/02/2017",
        LESID: "4"
      ]

    ]
  

]

【问题讨论】:

应该是 AA 抱歉,我更新了东西 thx。我试图结合 .map() 和 _gropuby。没有运气 这有帮助吗? 【参考方案1】:

创建了一个函数来做同样的事情,希望这会有所帮助-:

const custommodifier = (data) => Object.values(data.reduce((acc,KlasCode, ModuleID, ...participationData) => 
    if(acc[KlasCode])
        acc[KlasCode].Modules[0].Participation.push(
            ...participationData
        )
    
    else 
        acc[KlasCode] = 
            KlasCode,
            Modules: [
                ModuleID,
                Participation: [
                    ...participationData
                ]
            ]
        
    
    return acc;
, ));


let data = [
    KlasCode: "AA",
    LESDatum: "06/02/2017",
    LESID: "1",
    ModuleID: "1061",
    ParticipationLetterCode: "Y"
  , 
    KlasCode: "AA",
    LESDatum: "07/02/2017",
    LESID: "2",
    ModuleID: "1061",
    ParticipationLetterCode: "X",
  ,
  
    KlasCode: "AA",
    LESDatum: "13/02/2017",
    LESID: "3",
    ModuleID: "1061",
    ParticipationLetterCode: "Z"
  ,
  
    KlasCode: "BB",
    LESDatum: "16/02/2017",
    LESID: "4",
    ModuleID: "1062",
    ParticipationLetterCode: "X"
  
]
console.log(custommodifier(data))

【讨论】:

Abhisar,我一直在尝试将这个 reduce 函数用于类似的线程:你能帮我检查一下吗?:***.com/q/61610032/9248040thx【参考方案2】:

您可以采用动态方法,使用一组键广告组名称,然后从实际对象中取出键。最后,构建嵌套组后,将最终对象添加到最后一个组。

如有必要,此方法适用于更多嵌套组。

let data = [ KlasCode: "AA", LESDatum: "06/02/2017", LESID: "1", ModuleID: "1061", ParticipationLetterCode: "Y" ,  KlasCode: "AA", LESDatum: "07/02/2017", LESID: "2", ModuleID: "1061", ParticipationLetterCode: "X" ,  KlasCode: "AA", LESDatum: "13/02/2017", LESID: "3", ModuleID: "1061", ParticipationLetterCode: "Z" ,  KlasCode: "BB", LESDatum: "16/02/2017", LESID: "4", ModuleID: "1062", ParticipationLetterCode: "X" ],
    groups = [['KlasCode', 'Modules'], ['ModuleID', 'Participation']],
    result = data.reduce((r, o) => 
        groups
            .reduce((p, [key, group]) => 
                let value, temp;
                ( [key]: value, ...o  = o);
                temp = p.find(q => q[key] === value);
                if (!temp) p.push(temp =  [key]: value, [group]: [] );
                return temp[group];
            , r)
            .push(o);
        return r;
    , []);

console.log(result);
.as-console-wrapper  max-height: 100% !important; top: 0; 

【讨论】:

【参考方案3】:

我会使用groupBy 函数和Object.entries。您将需要使用它两次,以处理您的两个级别的分组。

您可以使用来自 lodash 的groupBy(或者来自 Ramda 的那个,或者其他任何地方),或者这里包含的简单的那个。

const groupBy = (fn) => (xs) => 
  xs .reduce((a, x) => (... a, [fn(x)]: [... (a [fn (x)] || []), x]), )

const transform = (data) => Object.entries (groupBy (x => x.KlasCode) (data))
  .map(([KlasCode, Modules]) => (
    KlasCode, 
    Modules: Object.entries(groupBy (x => x.ModuleID) (Modules))
      .map(([ModuleID, Participations]) => (
        ModuleID,
        Participation: Participations.map ((ParticipationLetterCode, KlasCode, ...rest) => rest)
      )
    )
  ))

let data1 = [KlasCode: "AA", LESDatum: "06/02/2017", LESID: "1", ModuleID: "1061", ParticipationLetterCode: "Y", KlasCode: "AA", LESDatum: "07/02/2017", LESID: "2", ModuleID: "1061", ParticipationLetterCode: "X", KlasCode: "AA", LESDatum: "13/02/2017", LESID: "3", ModuleID: "1062", ParticipationLetterCode: "Z", KlasCode: "BB", LESDatum: "16/02/2017", LESID: "4", ModuleID: "1063", ParticipationLetterCode: "X"]

console .log (transform (data1))
.as-console-wrapper min-height: 100% !important; top: 0

更新——Ramda 替代方案

我对上述解决方案和这里的其他答案并不感到兴奋。有时发生这种情况时,我会在 Ramda 中重写(免责声明:我是它的作者之一),然后将涉及的 Ramda 函数移植到 vanilla JS 中。这次我不打算做后者,但我将分享我如何利用像 Ramda 这样的库来做到这一点。我猜lodash中也有类似的功能。

const groupByProp = (propName, childName) => pipe (
  groupBy (prop (propName)),
  toPairs,
  map (evolve ([ , map (dissoc (propName))])),
  map (zipObj ([propName, childName]))
)

const transform = pipe (
  groupByProp('KlasCode', 'Modules'),
  map (evolve (Modules: groupByProp('ModuleID', 'Participation')))
)

let data1 = [KlasCode: "AA", LESDatum: "06/02/2017", LESID: "1", ModuleID: "1061", ParticipationLetterCode: "Y", KlasCode: "AA", LESDatum: "07/02/2017", LESID: "2", ModuleID: "1061", ParticipationLetterCode: "X", KlasCode: "AA", LESDatum: "13/02/2017", LESID: "3", ModuleID: "1062", ParticipationLetterCode: "Z", KlasCode: "BB", LESDatum: "16/02/2017", LESID: "4", ModuleID: "1063", ParticipationLetterCode: "X"]

console .log (transform (data1))
.as-console-wrapper min-height: 100% !important; top: 0
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
<script> const groupBy, prop, toPairs, map, evolve, dissoc, zipObj, pipe = R </script>

我觉得这些功能似乎更简单,更好地展示了转换的步骤。但这还不足以成为包含库的理由。但是一旦你遇到了一些这样的情况,图书馆似乎就很有意义了。

我并不是要在这里推 Ramda,只是要指出,当您拥有实用程序库的工具时,您通常可以编写更简单的代码。

【讨论】:

感谢 Scott 的建议。 你能帮我解决这个问题吗?:***.com/q/61610032/9248040

以上是关于javascript中定义一维数组,如何从TXT文件中为其赋值?的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript 如何定义一个二维数组

JavaScript 如何定义一个二维数组

matlab如何将一个一维数组从大到小排序

从 JavaScript 中的一维数组返回二维数组

动态数组c语言 求助!

JavaScript之数组