如何在JS中获取txt输入并将其转换为int数组?

时间:2018-12-02 15:08:43

标签: javascript arrays

请继续学习一些小知识,请仁慈。 如果在同一目录中有一些input.txt文件,则要提取该命令的命令是什么,然后如何将其转换为单独的值的数组?(不确定在JS中是否需要在方法中使用数字,之后我需要声明他们不是字符串吗?) 输入示例如下:
+4
-2
-47
+15
因此,只需将它们放在可行的var x = [4,-2,-47,15]中即可;只是为了简单起见,这就是我要的目的。

2 个答案:

答案 0 :(得分:0)

假设这是一个Node.js程序:

使用FS模块加载文件(如果您不关心并发,则readFileSync可能就足够了),使用string.split()在某些分隔符上分割结果字符串,然后使用parseInt(string,radix)将字符串转换成数字(JavaScript中没有整数类型)。将它们推入数组。

答案 1 :(得分:0)

如果您只想在本地运行此功能,则可以在现代浏览器中使用fetch

// Grab the file
fetch('text.txt')

  // Parse the contents to text
  .then(res => res.text())

  // call the `processText` function
  .then(processText)
  .catch(err => console.log(err));

function processText(text) {

  // Split the text into an array on the line break
  const arr = text.split('\n');

  // Convert each element into an integer
  // with the correct sign
  const mapped = arr.map(Number);
  console.log(mapped); // Array(4) [ 4, -2, -47, 15 ]
}