javascript - 如何在 JS 中从类中连接函数?
问题描述
我正在尝试解决Edabit上发布的挑战,但我遇到了一个我不太熟悉的语法。这是挑战所需的测试之一:
const ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // good so far
const p2 = new Pagination(ids, 5); // good so far
p2.getVisibleItems(); // good so far
p2.nextPage().getVisibleItems(); // what's going on here?
我可以猜测并说这可能是连接函数的一种方式......这是有道理的,但我不知道该怎么做。
这是我到目前为止所取得的成就。
class Pagination {
constructor(items, pageSize) {
this.items = items; // Holds the items array
this.pageSize = pageSize; // Holds the size of each page
this.totalPages = items.length; // Holds the total number of pages
this.currentPage = 0; // Holds the current page number
this.dicPages = {};
}
// Methods
// Goes to the previous page
prevPage() {
this.currentPage = this.currentPage - this.pageSize;
if (this.currentPage < 0) {
this.currentPage = 0;
}
return this.getVisibleItems();
}
// Goes to the next page
nextPage() {
this.currentPage = this.currentPage + this.pageSize;
return this.getVisibleItems();
}
// Goes to the first page
firstPage() {
this.currentPage = 0;
return this.getVisibleItems();
}
// Goes to the last page
lastPage() {
var pageIndex = (Object.keys(this.dicPages).length - 1) * this.pageSize;
this.currentPage = pageIndex;
return this.getVisibleItems();
}
// Goes to a page determined by the `page` argument
goToPage(page) {
this.currentPage = page;
return this.getVisibleItems();
}
// Returns the currently visible items as an array
getVisibleItems() {
var j = 0;
for (var i = 0, j = this.items.length; i < j; i += this.pageSize) {
this.dicPages[i] = this.items.slice(i, i + this.pageSize);
}
return this.dicPages[this.currentPage];
}
}
const ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const p2 = new Pagination(ids, 5);
console.log(p2.getVisibleItems()); //, [0, 1, 2, 3, 4]
console.log(p2.nextPage().getVisibleItems()); //, [5, 6, 7, 8, 9]
console.log(p2.nextPage().getVisibleItems()); //, [10]
解决方案
推荐阅读
- statistics-bootstrap - 如何在 r 中执行不同类型的引导程序?
- tsql - 在特定条件下生成字符串
- open-liberty - 无法使用 Open Liberty 18.0.0.4 构建可运行 Jar
- c# - 在 C:\Programs 文件中引用 dll 而不复制它
- python - 如何在matplotlib中设置三维轴之外的图例?
- javascript - jQuery FormBuilder:当屏幕折叠小于 482 像素时,有什么方法可以防止字段菜单转换为图标?
- django - 如何解决我的 CPU 利用率问题,我正在使用带有 nginx、uwsgi 和 django 的 ubuntu ec2 实例
- kubernetes - k8s pvc 中的 aws-efs “ProvisioningFailed - 没有卷插件匹配”
- java - 在方法中从 1-10 生成 3 个随机数字的问题
- angular - 如何将“名称”绑定到路由器插座以呈现动态创建的 angular-cdk 组件