Javascript 分页Javascript数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42761068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Paginate Javascript array
提问by SalmaFG
I am trying to write a Javascript function that takes an array, page_sizeand page_numberas parameters and returns an array that mimics paginated results:
我想写一个JavaScript函数,它接受一个array,page_size并page_number作为参数,并返回一个数组模仿分页结果:
paginate: function (array, page_size, page_number) {
return result;
}
so for example when:
例如,当:
array = [1, 2, 3, 4, 5],
page size = 2,
page_number = 2,
the function should return: [3, 4].
该函数应该返回:[3, 4]。
Any ideas would be appreciated.
任何想法,将不胜感激。
回答by casraf
You can use Array.prototype.sliceand just supply the params for (start, end).
您可以使用Array.prototype.slice并只为 提供参数(start, end)。
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));
console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));
回答by Dax Aquatic
Another aproach that you can utilize, is using .filter, look:
您可以使用的另一种方法是使用 .filter,查看:
const paginate = function (array, index, size) {
// transform values
index = Math.abs(parseInt(index));
index = index > 0 ? index - 1 : index;
size = parseInt(size);
size = size < 1 ? 1 : size;
// filter
return [...(array.filter((value, n) => {
return (n >= (index * size)) && (n < ((index+1) * size))
}))]
}
var array = [
{id: "1"}, {id: "2"}, {id: "3"}, {id: "4"}, {id: "5"}, {id: "6"}, {id: "7"}, {id: "8"}, {id: "9"}, {id: "10"}
]
var transform = paginate(array, 2, 5);
console.log(transform) // [{"id":"6"},{"id":"7"},{"id":"8"},{"id":"9"},{"id":"10"}]
回答by Filipe Madureira
You can use Array.filter()with the help of its second parameter (the index of the current element being processed in the array).
您可以在其第二个参数(数组中正在处理的当前元素的索引)的帮助下使用Array.filter()。
You'll also need the currently selected page and the number of items per page to display, so you can find the minimum and maximum index of the elements needed.
您还需要当前选择的页面和每页要显示的项目数,以便您可以找到所需元素的最小和最大索引。
const indexMin = selectedPage * elementsPerPage;
const indexMax = indexMin + elementsPerPage;
const paginatedArray = arrayToPaginate.filter(
(x, index) => index >= indexMin && index < indexMax
);
Updating the selectedPage and/or the elementsPerPage value will allow to return the correct items to display.
更新 selectedPage 和/或 elementsPerPage 值将允许返回要显示的正确项目。
回答by Ben Aston
The use of Array#sliceis the expected answer.
使用的Array#slice是预期的答案。
Here I use Symbol.iteratorto create an iterable.
在这里,我使用Symbol.iterator创建一个可迭代的.
const arr = [1,2,3,4,5,6,7,8,9,10]
function page({arr, pageSize, pageNumber}) {
const start = pageSize*(pageNumber-1)
const end = pageSize*pageNumber
return {
*[Symbol.iterator]() {
for(let i = start; i < arr.length && i < end; i++) {
yield arr[i]
}
}
}
}
console.log([...page({arr, pageSize: 5, pageNumber: 2})])
回答by dodov
Here's a solution with reduce():
这是一个解决方案reduce():
function paginate (arr, size) {
return arr.reduce((acc, val, i) => {
let idx = Math.floor(i / size)
let page = acc[idx] || (acc[idx] = [])
page.push(val)
return acc
}, [])
}
let array = [1, 2, 3, 4, 5]
let page_size = 2
let pages = paginate(array, page_size)
console.log(pages) // all pages
console.log(pages[1]) // second page
It returns an array of pages so you can get a certain page, or loop through all of them.
它返回一个页面数组,以便您可以获取某个页面,或遍历所有页面。
回答by JustinStoddard
I saw an example above that did this correctly (kind of) and wanted to expand on it.
我在上面看到了一个例子,它正确地(有点)做到了这一点,并想对其进行扩展。
This was the example.
这就是例子。
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
There are a few things wrong with this.
这有一些问题。
1.) If the page_numberis 0 then it will try and set the starting split at -1 * page_sizewhich returns an empty array. So the minimum value of the page_numberattr should be 1, never anything less unless you handle that case in the function.
1.) 如果page_number是 0,那么它将尝试设置-1 * page_size返回空数组的起始拆分。所以page_numberattr的最小值应该是 1,除非你在函数中处理这种情况,否则永远不会小于 1。
2.) The starting and ending index of the split are the same. Because of this, you get back an empty array. So the split should be:
2.) 分割的开始和结束索引是相同的。因此,您会返回一个空数组。所以拆分应该是:
return array.split(page_number * page_size, page_number * page_size + page_size)
const myArray = [1,2,3,4,5,6,7,8,9,10];
const paginateBad1 = (array, page_size, page_number) => {
return array.slice((page_number - 1) * page_size, page_number * page_size);
};
const paginateBad2 = (array, page_size, page_number) => {
return array.slice(page_number * page_size, page_number * page_size);
};
const paginateGood = (array, page_size, page_number) => {
return array.slice(page_number * page_size, page_number * page_size + page_size);
};
console.log("Bad 1", paginateBad1(myArray, 2, 0));
console.log("Bad 2", paginateBad2(myArray, 2, 1));
console.log("Good", paginateGood(myArray, 2, 1));

