飞镖列表否定索引不起作用

时间:2019-01-20 16:17:26

标签: dart

Dart的List结构似乎不支持负索引。这背后的原因是什么?我曾经使用的所有其他语言都支持此功能。为什么dart决定排除这种基本结构?

以下代码-

void main() {
    List<String> x = ["foo", "bar"];
    print(x[-1]);
}

生产-

Uncaught exception:
RangeError (index): Index out of range: index must not be negative: -1

2 个答案:

答案 0 :(得分:2)

Dart不支持负索引。

要访问相对于末尾的元素,您可以使用来计算索引

print(x[x.length - 1])

您可以在https://github.com/dart-lang/sdk中创建功能请求,以获得语言设计者的反馈。

答案 1 :(得分:2)

要打印最后一个元素,只需使用:

print(x.last);