我需要遵循一定的模式:
下面的示例只是示例,但實際上該陣列可以是任意大小,例如 100 個專案長,并且可以洗掉任何專案,例如 100 個專案中的第 55 個。
添加第一項:
const items = [1]
添加第二項:
const items = [1, 2]
洗掉第二項(在本例中為 2):
const items = [1]
添加第三項
const items = [1, 3]
所以換句話說,每次我添加一個專案時,它應該加 1。
但是當我從陣列中洗掉一個專案,然后添加一個新專案時,我需要記住之前添加的數字并添加 1。
另一個例子:
const items = [3, 4]
添加專案:
const items = [3, 4, 5]
洗掉第一項(在本例中為 3):
const items = [4, 5]
添加新專案:
const items = [4, 5, 6]
謝謝 :)
uj5u.com熱心網友回復:
您必須使用變數跟蹤計數,然后在每次附加到陣列時使用該變數(確保每次都增加它):
let count = 1;
const items = [];
const appendAndIncrementCount = () => {
items.push(count);
count = 1;
};
const log = () => console.log(JSON.stringify(items));
// "add first item"
appendAndIncrementCount();
log(); // [1]
// "add second item"
appendAndIncrementCount();
log(); // [1,2]
// "remove second item"
items.splice(1, 1);
log(); // [1]
// "add third item"
appendAndIncrementCount();
log(); // [1,3]
// ...etc.
請注意,您也可以簡單地使用閉包來代替閉包array.push(count );,但我使用閉包來說明您可以自定義操作的功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/497962.html
標籤:javascript 数组
下一篇:將for回圈縮短為一個
