![](/img/trans.png)
[英]Find value and index of Javascript array element when the index meets another condition
[英]JS - React - map() method filter on element index (only run if index meets condition)
我有一個我想要迭代的列表。 並且基於它的索引它應該做一些事情。 它過濾它:
現在我有以下代碼。 它正在發揮作用。 但這並不有效。 因為它遍歷整個數組 3 次。 有沒有辦法過濾這個?
問題的核心:
block.blockGrid.map((blockItem, index) => {
if (index > 0 && index <= (newArrayLength / 2)) {
<BlockGridElementFirstHalf key item={blockItem} index={index}/>
}
})
完整代碼:
class BlockGrid extends React.Component {
render() {
let {block} = this.props;
const newArrayLength = (block.blockGrid.length % 2 === 0) ? block.blockGrid.length : block.blockGrid.length + 1;
return (
<React.Fragment>
<Row>
<Col xs={6}>
{/*only run element 0 */}
{block.blockGrid &&
block.blockGrid.map((blockItem, index) => {
if (index === 0) {
return <BlockGridElementZero key item={blockItem} index={index}/>
}
})}
{/* only run element from 1 to half of length */}
{block.blockGrid &&
block.blockGrid.map((blockItem, index) => {
if (index > 0 && index <= (newArrayLength / 2)) {
<BlockGridElementFirstHalf key item={blockItem} index={index}/>
}
})}
</Col>
</Row>
<Row>
<Col xs={6}>
{/* only run element from half of length up to last */}
{block.blockGrid &&
block.blockGrid.map((blockItem, index) => {
if (index > (newArrayLength / 2)) {
<BlockGridElementLastHalf key item={blockItem} index={index}/>
}
})}
</Col>
</Row>
</React.Fragment>
)
}
}
你能檢查一下這個代碼片段嗎? https://stackblitz.com/edit/react-ygwbah
您可以像這樣過濾地圖:
myArray
.filter((el, i) => (i === 0 ))
.map((element, index) => {
// do my code
})
}
試試這個,讓我知道這是否有幫助。 它只會遍歷您的項目一次 -
class BlockGrid extends React.Component {
render() {
let row1 = [], row2 = [];
block.blockGrid && block.blockGrid.forEach((element, i) => {
if (i == 0) {
rows1.push(<BlockGridElementZero key item={blockItem} index={i} />);
}
else if (i > 0 && i <= (newArrayLength / 2) {
rows1.push(<BlockGridElementFirstHalf key item={blockItem} index={i} />);
}
else {
rows2.push(<BlockGridElementLastHalf key item={blockItem} index={i} />);
}
});
return (
<>
<Row>
<Col xs={6}>
{row1}
</Col>
</Row>
<Row>
<Col xs={6}>
{row2}
</Col>
</Row>
</>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.