切片数组在javascript中一次列出五个元素



更新:下面的代码并没有按照我想要的方式工作,就像我在下面提到的那样,当用户点击按钮时,它应该一次显示五个项目。

我正在尝试使用javascript切片方法(如果这不是正确的使用方式,请建议),数组列表一次显示五个数组项,我已经创建了代码笔示例来显示我正在尝试做的

假设我有20张唱片,如果用户第一次点击,我应该得到1-5个数组项目如果用户第二次点击,我应该得到5-10。。。。。等等。

https://codepen.io/TLJens/pen/NPZyYR

这里的代码:

$('#loading').hide();
var counts = 0;
var displayCount = 5;
var starting = 0;
var data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
function slicemydata(sstart, totalsize, eend) {  
var items = []; debugger;
if (totalsize <= data.length) {
if (eend == 0) {
items = data.slice(sstart,totalsize);
} else { 
if (sstart > eend) {
eend = data.length;
}
items = data.slice(sstart, eend);
sstart =  displayCount + 5;
}
}
console.log(items);
$('.js-lazy-load-data').append(items);
}
$('.js-lazy-load').click(function () {

counts++;
slicemydata(starting,data.length,displayCount);

$('.js-lazy-load').fadeOut();

// Minor timeout before showing loader
// setTimeout(function () {
//     $('#loading').fadeIn();
// }, 400); 

// Simulate server call by showing loading gif  
// for 2.5 seconds before displaying results
//setTimeout(function () {
//    $('#loading').fadeOut();
//}, 2600); 

// Display results after 3 seconds
setTimeout(function () {
//$('.js-lazy-load-data').append(data);
$('.js-lazy-load').show();
}, 1000);  
});

这可能是Generators和生成器函数的用例;OP的任务至少是一个很好的实践练习。。。

function* createChunkGenerator(
itemList, chunkSize = 1, chunkCount = 0
) {
// sanitize and decouple (shallow copy) the passed
// array reference, thus one can `splice` the list
// without mutating the original array.
itemList = Array.from(itemList ?? []);
chunkSize = Math.max(chunkSize, 1);
while (itemList.length >= 1) {
++chunkCount;
yield {
chunkCount,
itemList: itemList.splice(0, chunkSize),
};
}
}

let chunkGenerator = createChunkGenerator(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 5
);
let chunks;
console.log('...automatically tiggered `next` based iteration...');
while (chunks = chunkGenerator.next().value) {
const { chunkCount, itemList } = chunks;
console.log({ chunkCount, itemList });
}

chunkGenerator = createChunkGenerator(
[1, 2, 3, 4, 5, 6, 7, 8], 6
);
console.log('...explicitly (e.g. event) triggered `next` based iteration...');
console.log(
chunkGenerator.next()
);
console.log(
chunkGenerator.next()
);
console.log(
chunkGenerator.next()
);
console.log(
chunkGenerator.next()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

下面的DOM/DOM事件实现演示了基于生成器的分页器/分页的方便用法。

function* createChunkGenerator(
itemList, chunkSize = 1, chunkCount = 0
) {
// sanitize and decouple (shallow copy) the passed
// array reference, thus one can `splice` the list
// without mutating the original array.
itemList = Array.from(itemList ?? []);
chunkSize = Math.max(chunkSize, 1);
while (itemList.length >= 1) {
++chunkCount;
yield {
chunkCount,
itemList: itemList.splice(0, chunkSize),
};
}
}
function handleCreateLoadItemsFromBoundData({ currentTarget }) {
const { generator: chunkGenerator, elmOutput } = this;
const chunks = chunkGenerator.next().value ?? null;

if (chunks !== null) {
const { chunkCount: loadCount, itemList: loadItems } = chunks;
elmOutput.value =
`... loadCount: ${ loadCount }, loadItems: ${ loadItems } ...`;
} else {
elmOutput.value =
'... no more load items ...';
currentTarget.disabled = true;
}
}
document
.querySelector('button')
.addEventListener(
'click',
handleCreateLoadItemsFromBoundData.bind({
generator: createChunkGenerator(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 5
),
elmOutput: document.querySelector('output'),
})
);
<button>load items</button>
=>
<output>...</output>

以下是我将如何处理它。

  1. 传入需要更新为函数的数据和元素。

  2. 该函数初始化索引,并返回一个新函数,该函数充当侦听器的处理程序。

  3. 在该函数的主体中,您使用切片数据编写新的HTML,然后更新元素。

const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
// Cache the elements
const div = document.querySelector('div');
const button = document.querySelector('button');
// Call `slicer` with the data, and the element to be updated.
// `slicer`returns a new function that is assigned to the listener
button.addEventListener('click', slicer(data, div), false);
// `slicer` accepts some data, and the 
// element to be updated
function slicer(data, div) {
// Initialises the `index` which is
// scoped to the returning function. No
// need for global variables!
let index = 0;
// Returns a function that keeps a record
// of index so it can update it
return function () {
if (index < data.length) {

// `slice` the data from the current
// index, `map` over that array to create
// some HTML, and then join it up
const html = data
.slice(index, index + 5)
.map(el => `<span>${el}</span>`)
.join(', ');
// Add that to the element that needs updating
div.innerHTML = `<div>${html}</div>`;

// Finally increase the index
index += 5;

} else {

console.log('No more data');

}

}
}
<button>Click me!</button>
<div></div>

附加文件

  • 关闭

  • map

  • 模板/字符串文字

所以我认为,如果你只想对数据进行分页,那么只需跟踪当前的"pageIndex";你上了多久,每个";页面";这样,你在数组中的起始位置就是pageIndex * pageSize,而你在数组的结束位置就是start + pageSize。然后,要获得下一页或上一页,只需相应地增加/减少页面索引即可。我将把显示数据的练习留给您,因为这与您需要帮助的内容无关。希望这能有所帮助!

let data = [1,2,3,4,5,6,7,8,9,10,11,12,13];
let currentPage = 0;
let pageSize = 5;
function getPage(data, pageSize, pageIndex) {
let start = pageSize * pageIndex;
return data.slice(start, start + pageSize) 
}
console.log(getPage(data, pageSize, currentPage));
currentPage++;
console.log(getPage(data, pageSize, currentPage));
currentPage++;
console.log(getPage(data, pageSize, currentPage));
currentPage++;
console.log(getPage(data, pageSize, currentPage));
currentPage++;

最新更新