Off by one errors
错误(有时称为 OBOE)。JavaScript 索引从0
开始,而不是1
,这意味着最后一个索引总会比字符串或数组的长度少 1。如果尝试访问等于长度的索引,程序可能会抛出“索引超出范围”引用错误或打印出undefined
。
当使用将索引范围作为参数的字符串或数组方法时,阅读相关的文档并了解参数中的索引的包含性(即是否考虑进返回值中)很重要。以下是一些错误的示例:
```js
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let len = alphabet.length;
for (let i = 0; i <= len; i++) {
// 在最后多了一次循环
console.log(alphabet[i]);
}
for (let j = 1; j < len; j++) {
// 循环少了一次,漏掉了索引 0 处的字符
console.log(alphabet[j]);
}
for (let k = 0; k < len; k++) {
// 不多不少,这才是正确的
console.log(alphabet[k]);
}
```