簡體   English   中英

javascript數組重新開始計數

[英]javascript array restart counting

我有這段代碼:

  //var data.name is declared somewhere else, e.g. "Sherlock". It changes  often.
  recents[recents.length] = data.name;
  idThis = "recent" + recents.length;
  if(recents.length >= 7) {
  recents[0]=recents[7];
  recents[1]=recents[8];
  recents[2]=recents[9];
  recents[3]=recents[10];
  recents[4]=recents[11];
  recents[5]=recents[12];
  recents[6]=recents[13];
  recents[7]=recents[14];
  recents[0]=recents[15];
  recents[1]=recents[16];
  recents[2]=recents[17];
  //etc
  idThis = "recent" + (recents.length -7);
}
document.getElementById(idThis).innerHTML = data.name;

我的問題是如何自動執行recents[0]=recents[7] recents[1]=recents[8]等? 關鍵是recent ID不能大於6,否則其余代碼將無法工作。

在我看來,您想要從原始數組中獲取切片 我不確定您要哪個切片,但是以下是獲取前8個項目和后8個項目的方法,也許其中之一就是您想要的:

// Get the first 8 items from recents.
var first8 = recents.slice(0, 8);
// Get the last 8 items from recents.
var last8 = recents.slice(-8);
// first8 and last8 now contain UP TO 8 items each.

當然,如果您的recents數組沒有8個項目,則slice的結果將少於8個項目。

如果要刪除recents數組中的范圍,可以使用splice

// Delete the first 8 items of recents.
recents.splice(0, 8);
// recents[0] is now effectively the value of the former recents[8] (and so on)

您還可以使用splice的返回值來獲取已刪除的項目:

// Delete and get the first 8 items of recents.
var deletedItems = recents.splice(0, 8);
// You could now add them to the end, for example:
recents = recents.concat(deletedItems);

在里面:

varfruits = [“香蕉”,“橙色”,“蘋果”,“芒果”];

添加最后一個元素:

fruits.push("Kiwi");

香蕉,橘子,蘋果,芒果,獼猴桃

刪除第一個元素:

fruits.shift();

橙,蘋果,芒果,獼猴桃

解:

function add(fruit) {
    if(fruits.length > 6) {
        fruits.shift();
        fruits.push(fruit);
    }
}

只要這樣做:

for (i = 0; i < recents.length; i++) { 
    recents[i]=recents[i % 7];
}

暫無
暫無

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

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