如何转换此数组:
let strArr = ["10100", "10111", "11111", "01010"];
成二维数组。
二维数组将是:-
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
0 1 0 1 0
答案 0 :(得分:3)
您可以从字符串和映射号中获得可迭代项。
var array = ["10100", "10111", "11111", "01010"],
matrix = array.map(s => Array.from(s, Number));
console.log(matrix);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
如果结果需要是每个字符串的每个字符包含一个元素的数组数组,则可以在循环或映射中将每个字符串与空字符串分开。
let res = [];
let strArr = ["10100", "10111", "11111", "01010"];
strArr.map((str) => {
res.push(str.split(''))
});
console.log(res);
答案 2 :(得分:0)
遍历每个项目并将其内容分散到一个数组中-然后转换为数字。
let newArr = strArr.map(item => [...item].map(Number));
答案 3 :(得分:0)
let inArr = ["10100", "10111", "11111", "01010"];
let outArr = inArr.map( line => line.split("").map( item => +item ) );
console.log(outArr);
let inArr = ["10100", "10111", "11111", "01010"];
let outArr = inArr.map( line => line.split("").map( item => +item ) );
答案 4 :(得分:0)
这样,您将获得一个二维数组,其中包含零和一
const newArr = strArr.map((a) => a.split("").map(char => char === "0"? 0: 1))
答案 5 :(得分:0)
let strArr = ["10100", "10111", "11111", "01010"];
let numColumns = strArr[0].length;
let numRows = strArr.length;
let string = strArr.join('');
let result = [];
for (let row = 0; row < numRows; row++) {
result.push([]);
for (let column = 0; column < numColumns; column++) {
result[row].push(parseInt(string.charAt(row*5 + column), 10));
}
}
console.log(result);