切片数组在 javascript 中一次列出五个元素
slicing array list five elements at a time in 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);
});
所以我认为,如果您只想对数据进行分页,则只需跟踪您所在的当前“pageIndex”以及每个“页面”的长度,即可轻松完成。这样,您在数组中的起始位置就是 pageIndex * pageSize
,而您在数组中的结束位置就是 start + pageSize
。然后,要获得下一页或上一页,您所要做的就是 increment/decrement 相应的页面索引。我将把显示数据的练习留给您,因为这与您需要帮助的内容无关。希望这对您有所帮助!
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++;
以下是我的处理方法。
将需要更新的数据和元素传入一个函数
该函数初始化索引,returns 一个新函数充当侦听器的处理程序。
在该函数的主体中,您使用切片数据编写新的 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>
其他文档
这可能是 Generator
s and generator functions 的用例; 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 事件实现演示了基于 paginator/pagination.
的生成器的便捷用法
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>
更新: 下面的代码没有按照我想要的方式工作,就像我在下面提到的那样,当用户单击按钮时它应该一次显示五个项目。
我正在尝试使用 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);
});
所以我认为,如果您只想对数据进行分页,则只需跟踪您所在的当前“pageIndex”以及每个“页面”的长度,即可轻松完成。这样,您在数组中的起始位置就是 pageIndex * pageSize
,而您在数组中的结束位置就是 start + pageSize
。然后,要获得下一页或上一页,您所要做的就是 increment/decrement 相应的页面索引。我将把显示数据的练习留给您,因为这与您需要帮助的内容无关。希望这对您有所帮助!
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++;
以下是我的处理方法。
将需要更新的数据和元素传入一个函数
该函数初始化索引,returns 一个新函数充当侦听器的处理程序。
在该函数的主体中,您使用切片数据编写新的 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>
其他文档
这可能是 Generator
s and generator functions 的用例; 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 事件实现演示了基于 paginator/pagination.
的生成器的便捷用法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>