-
繁星点点滴滴
假设所有行具有相同数量的元素,您可以首先从文本构造一个二维数字数组,然后使用Array.from获取每列中的元素。let myText = `1,5,92,6,03,7,04,8,0`;const parts = myText.split('\n').map(x => x.split(',').map(Number));const res = Array.from({length: parts[0].length}, (_,i)=>Array.from({length: parts.length}, (_,j)=>parts[j][i]));console.log(JSON.stringify(res));
-
交互式爱情
这是一个更优化的版本(更快一点),迭代次数更少。const myText = `1,5,9 2,6,03,7,04,8,0`;const rows = myText.split('\n');const result = [];for (let i = 0; i < rows.length; i++) { const row = rows[i].split(','); for (let j = 0; j < row.length; j++) { if (result[j] === undefined) { result[j] = [parseInt(row[j])] } else { result[j].push(parseInt(row[j])) } }}console.log(result)
-
萧十郎
您可以使用split,map和reduce:const myText = `1,5,92,6,03,7,04,8,0`;const my2DArray = myText .split('\n') .map(row => row.split(',').map(Number)) // Reversed 2D Array .reduce((acc, row) => { if (acc.length) { return acc.map((r, i) => r.concat(row[i])); } return row.map(v => [v]); }, []); // Rotated matrix console.log(my2DArray);