例如,我知道如何使用 JavaScript for 循环循环遍历数组,但我仍然不明白 array.length -1
的含义,特别是 -1
部分。
当在数组上使用 for 循环时,我们有这样的事情:
for (i = 0; i < array.length; i++) {...}
但有时我也看到过这样的事情:
for (i = 0; i < array.length - 1; i++) {...}
第二种情况,为什么array.length中会有“-1”,它有什么作用?还有为什么有时显示有时不显示?
最佳答案
这是为了防止 fencepost 错误,也就是“off-by-one”。
常见试题:
You are required build 100 meters of fence, with a fence post every meter. How many fenceposts will you need?
明显的快速(错误)答案:
100 meters
--------------- = 100 posts
1 post
------
meter
因为 100 米的栅栏需要 101 个柱子:
Distance: 1 2 .... 99 100
|-|-|.....| - | - |
Post: 1 2 3 ....99 100 101
现在对于数组,同样的事情也会发生。假设这是一个包含 5 个项目的数组:
for (i = 0 ; i <= 5; i++)
^--length of array
你最终做了
i: 0, 1, 2, 3, 4, 5
iteration: 1 2 3 4 5 6
糟糕。 5 项数组,但您已经执行了 6 次循环 - 一次太多了。
您可以通过两种方式修复错误:
for (i = 0; i < length; i++)
^---change from "<=" to "<"
或
for (i = 0; i <= length - 1; i++)
^---change the upper limit value.
关于javascript - "array.length -1"在 JavaScript 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35024593/