[英]Text File to JavaScript Nested Array
我有 this.txt 文件更改为嵌套数组:
000011000000
000100001100
000001100001
010010001000
100101000100
101010010001
001000001001
000001000111
010100100010
010010010010
000000011100
001001110000
格式:
var data = [
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1],
[0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0]
]
到目前为止我所做的是:
function readMatrixFile(){
var inputElement = document.getElementById("adjencyMatrixInput");
var fileList = inputElement.files;
var plainMatrix = new FileReader();
plainMatrix.readAsText(fileList[0]);
plainMatrix.onload = function () {
//Add to Matrix
renderMatrix(plainMatrix)
}
}
和 2. 拆分文件
function renderMatrix(plainMatrix) {
var matrix = plainMatrix.result;
var mtx = [];
matrix = matrix.split("\n");
}
我知道我需要通过 for 循环,但不确定如何获取嵌套数组。
用换行符分割字符串,然后在每个项目上使用 map并将字符串转换为具有扩展语法的字符数组。
const str = `000011000000 000100001100 000001100001 010010001000 100101000100 101010010001 001000001001 000001000111 010100100010 010010010010 000000011100 001001110000` const res = str.split("\n").map(e => [...e]) console.log(res)
要将字符转换为数字,map 在字符数组上并解析每个项目:
const str = `000011000000 000100001100 000001100001 010010001000 100101000100 101010010001 001000001001 000001000111 010100100010 010010010010 000000011100 001001110000` const res = str.split("\n").map(e => [...e].map(e => +e)) console.log(res)
您将matrix
转换为一串一和零,您只需要拆分字符串并将它们转换为数字
function renderMatrix(plainMatrix) {
var matrix = plainMatrix.result;
var mtx = matrix.split("\n"); // mtx is now an array of strings of ones and zeros
mtx = mtx.map(string => string.split('')); // mtx is now an array of arrays of number string
mtx = mtx.map(nested => nested.map(numberString => Number(numberString))); // mtx is now what you want
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.