簡體   English   中英

如何在數組中的特定索引處插入元素或組件?

[英]How do I insert an element or component in an array at a specific index?

我有一個包含 25 個項目(會增加)的數組,我想將它分成 10 個塊。 在第一個塊之后,我想在 10 個的第二個塊之后插入一個圖像和一個組件。分享我到目前為止編寫的代碼。

const DESKTOP_SPLIT = 10;

  handleSplit = () => {
    const { listings } = this.props;
    let finalArr = [[]];
    let currentArr = 0;
    const myArray = [...listings];
    

    for (let i = 0; i < listings.length; i++) {
      if (i % DESKTOP_SPLIT === 0) {
        currentArr += 1;
        
        if (!finalArr[currentArr]) {
          finalArr[currentArr] = [];
        }
      }
      finalArr[currentArr].push(i);
    }
    return finalArr;
  };

Expected output:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [<SomeComponent />],
 [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
 [Some image],
 [21, 22, 23, 24, 25, ...]
]

在上面的代碼中, myArray 變量包含我想要拆分的數組。 我該如何繼續並在數組中的每 10 個元素之后動態插入一個元素/組件?

不完全確定我是否理解,但您可能可以使用Array.splice方法來實現您的目標。 下面是一些代碼,它將在數組中的每第二個元素之后插入字符串'SPLICE'

const SPLICE_AFTER = 2;
const data = ['One', 'Two', 'Three', 'Four', 'Five'];

const result = [...data];

for (let i = result.length - (result.length % SPLICE_AFTER); i > 0; i -= SPLICE_AFTER) {
  result.splice(i, 0, 'SPLICE');
}

// Produces: ["One", "Two", "SPLICE", "Three", "Four", "SPLICE", "Five"]
console.log(result);

請注意,您必須從后到前執行此操作,因為每次執行插入后數組都會增長。


編輯:感謝您澄清評論-我誤解了您所指的拆分部分。 您可以使用Array.slice方法來實現您的目標:

const CHUNK_SIZE = 2;
const data = ['One', 'Two', 'Three', 'Four', 'Five'];

// This will be a two-dimensional array
const result = [];

for (let i = 0; i < data.length; i += CHUNK_SIZE) {
  const chunk = data.slice(i, i + CHUNK_SIZE);
  chunk.push("SPLICE");
  result.push(chunk);
}

// Produces: [
//   ['One', 'Two', 'CHUNK'], 
//   ['Three', 'Four', 'CHUNK'], 
//   ['Five', 'CHUNK']
// ]
console.log(result);

它在 CodeSandbox 上運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM