我有以下数据数组:
var arr = [ [ 2, 3, 4, 5, 6, 7 ],
[ 8, 9, 10, 11, 12, 13 ],
[ 14, 15, 16, 17, 18, 19 ],
[ 20, 21, 22, 23, 24, 25 ],
[ 26, 27, 28, 29, 30, 31 ]];
我可以将数据输出到水平视图中,但是想要创建一个垂直视图。
var Hello = React.createClass({
tablerows: function() {
return this.props.arr.map(rows => {
var row = rows.map(cell => <td>{cell}</td>);
return(
<tr>{row}</tr>
);
});
},
render: function() {
return <table>{this.tablerows()}</table>;
}
});
答案 0 :(得分:2)
您可以转换数组并使用交换索引处的值来构建一个新数组。
var array = [ [ 2, 3, 4, 5, 6, 7 ], [ 8, 9, 10, 11, 12, 13 ], [ 14, 15, 16, 17, 18, 19 ], [ 20, 21, 22, 23, 24, 25 ], [ 26, 27, 28, 29, 30, 31 ]],
result = array.reduce((r, a, i) =>
(a.forEach((b, j) => (r[j] = r[j] || [])[i] = b), r), []);
console.log(result);
答案 1 :(得分:2)
您可以转置&#34;矩阵&#34;如下
let arr = this.props.arr;
let transArr = arr[0].map( (_, c) => arr.map(r => r[c]));
return transArr.map(rows => { ... })
示例代码:
var arr = [ [ 2, 3, 4, 5, 6, 7 ],
[ 8, 9, 10, 11, 12, 13 ],
[ 14, 15, 16, 17, 18, 19 ],
[ 20, 21, 22, 23, 24, 25 ],
[ 26, 27, 28, 29, 30, 31 ],
[ 32, 33, 34, 35, 36, 37 ],
[ 38, 39, 40, 41, 42, 43 ],
[ 44, 45, 46, 47, 48, 49 ],
[ 50, 51, 52, 53, 54, 55 ],
[ 56, 57, 58, 59, 60, 61 ],
[ 62, 63, 64, 65, 66, 67 ],
[ 68, 69, 70, 71, 72, 73 ],
[ 74, 75, 76, 77, 78, 79 ],
[ 80, 81, 82, 83, 84, 85 ],
[ 86, 87, 88, 89, 90, 91 ],
[ 92, 93, 94, 95, 96, 97 ],
[ 98, 99, 100, 101, 102, 103 ],
[ 104, 105, 106, 107, 108, 109 ] ];
var Hello = React.createClass({
tablerows: function() {
let arr = this.props.arr;
let transArr = arr[0].map( (_, c) => arr.map(r => r[c]));
return transArr.map(rows => {
var row = rows.map(cell => <td>{cell}</td>);
return(
<tr>{row}</tr>
);
});
},
render: function() {
return <table>{this.tablerows()}</table>;
}
});
ReactDOM.render(
<Hello arr={arr} />,
document.getElementById('container')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
&#13;
更新了jsfiddle
答案 2 :(得分:1)
您可以尝试这样的事情:
arr
并获取最大长度,以便知道最大列数。rows
。td
并使用父循环中的索引来获取项目。
var arr = [ [ 2, 3, 4, 5, 6, 7 ],
[ 8, 9, 10, 11, 12, 13 ],
[ 14, 15, 16, 17, 18, 19 ],
[ 20, 21, 22, 23, 24, 25 ],
[ 26, 27, 28, 29, 30, 31 ]];
var Hello = React.createClass({
tablerows: function() {
const max = Math.max.apply(null, this.props.arr.map(x => x.length));
return Array.from({length: max}, function(item, index){
return <tr>
{
arr.map(x => <td>{x[index]}</td>)
}
</tr>
})
},
render: function() {
return <table>{this.tablerows()}</table>;
}
});
ReactDOM.render(<Hello arr={arr}/>, document.querySelector('.content'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div class='content'></div>