You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS分页函数转Dart及三元运算符逐行解析请求

JavaScript分页函数解析及Dart转换

一、原JavaScript代码逐行解析

先看原函数代码:

const getPagination = (page, size) => {
  const limit = size ? +size : 3
  const from = page ? page * limit : 0
  const to = page ? from + size - 1 : size - 1

  return { from, to }
}

逐行拆解逻辑:

  • const getPagination = (page, size) => {
    定义箭头函数getPagination,接收两个参数:page(当前页码)、size(每页数据条数)。

  • const limit = size ? +size : 3
    三元运算符判断:若size有有效值(非空、非0),则把size转为数字类型(+size是JS快速转数字的写法);若无有效值,默认每页显示3条。结果赋值给limit(实际每页条数)。

  • const from = page ? page * limit : 0
    三元运算符判断:若page有有效值,计算当前页的起始数据索引(页码×每页条数);若无有效值,起始索引默认0(对应第一页的起始位置)。

  • const to = page ? from + size - 1 : size - 1
    三元运算符判断:若page有有效值,计算当前页的结束数据索引(起始索引+每页条数-1,因为数据索引从0开始);若无有效值,结束索引默认是size-1(对应默认第一页的最后一条数据索引)。

  • return { from, to }
    返回包含起始索引from和结束索引to的对象。

二、对应的Dart实现代码

Map<String, int> getPagination(int? page, int? size) {
  final int limit = size != null ? size : 3;
  final int from = page != null ? page * limit : 0;
  final int to = page != null ? from + (size ?? 3) - 1 : (size ?? 3) - 1;

  return {'from': from, 'to': to};
}

Dart版本说明:

  • 参数声明为int?,表示允许传入null,对应JS中参数可能未传递的情况。
  • size ?? 3是Dart的空合并运算符,作用和JS三元逻辑一致:若size为null则使用默认值3。
  • 返回Map<String, int>类型,对应JS中的返回对象结构。

内容的提问来源于stack exchange,提问作者Tony Hart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:15:51