2.9 KiB
2.9 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7b86367417b2b2512b3b | Catch Off By One Errors When Using Indexing | 1 | 使用索引时捕获一个错误 |
Description
Off by one errors
(有时称为OBOE)。 JavaScript索引从零开始,而不是一个,这意味着最后一个索引总是小于项目的长度。如果您尝试访问等于长度的索引,程序可能会抛出“索引超出范围”引用错误或打印undefined
。当您使用将索引范围作为参数的字符串或数组方法时,它有助于阅读文档并了解它们是否包含(指定索引处的项目是否是返回的一部分)。以下是一些错误的示例: let alphabet =“abcdefghijklmnopqrstuvwxyz”;
让len = alphabet.length;
for(let i = 0; i <= len; i ++){
//最后循环一次太多次
的console.log(字母[I]);
}
for(let j = 1; j <len; j ++){
//循环一次太少次并错过索引0处的第一个字符
的console.log(字母[J]);
}
for(let k = 0; k <len; k ++){
// Goldilocks赞成 - 这是正确的
的console.log(字母表[K]);
}
Instructions
Tests
tests:
- text: 您的代码应该设置循环的初始条件,以便从第一个索引开始。
testString: 'assert(code.match(/i\s*?=\s*?0\s*?;/g).length == 1, "Your code should set the initial condition of the loop so it starts at the first index.");'
- text: 您的代码应该修复循环的初始条件,以便索引从0开始。
testString: 'assert(!code.match(/i\s?=\s*?1\s*?;/g), "Your code should fix the initial condition of the loop so that the index starts at 0.");'
- text: 您的代码应设置循环的终端条件,以便它停在最后一个索引处。
testString: 'assert(code.match(/i\s*?<\s*?len\s*?;/g).length == 1, "Your code should set the terminal condition of the loop so it stops at the last index.");'
- text: 您的代码应该修复循环的终端条件,使其在长度之前停止在1。
testString: 'assert(!code.match(/i\s*?<=\s*?len;/g), "Your code should fix the terminal condition of the loop so that it stops at 1 before the length.");'
Challenge Seed
function countToFive() {
let firstFive = "12345";
let len = firstFive.length;
// Fix the line below
for (let i = 1; i <= len; i++) {
// Do not alter code below this line
console.log(firstFive[i]);
}
}
countToFive();
Solution
// solution required