[英]How would I limit the # of search results to 10 with each item added into an array removed?
我創建了一個 for 循環來限制我的列表只顯示最后 10 個搜索結果,但似乎無法關閉 object 數組的 shift() index[0],因此最早的結果被刪除,最新的結果位於數組的末尾:
for (let i = 0; i < searchHistory.length; i++) {
if (searchHistory.length > 10) {
console.log(searchHistory[i]);
searchHistory[i].shift();
}
}
searchHistory 的 console.log = Object 數組
searchHistory[i] 的 console.log = Console Log
如果您的目標是限制數組的長度,則不需要循環; slice()
可以為您做到:
searchHistory = searchHistory.slice(-10);
請注意,這也消除了對if
條件的需要。
要將數組限制為最后 10 個元素,請使用:
searchHistory.slice(-10);
所以要顯示最后 10 次使用:
if( searchHistory.length > 10 ) {
searchHistory.slice(-10).forEach(s => console.log( s ));
}
演示
const searchHistory = [4,5,6,67,32,1,3,4,5,9,10,12,13,4,66,67,78,90]; //Display the last 10 all at once - array console.log( searchHistory.slice(-10) ); //Display last 10, one at a time if( searchHistory.length > 10 ) { searchHistory.slice(-10).forEach(s => console.log( s )); }
您可以使用 splice() 來限制您想要的項目數量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.