freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.chinese.md

2.9 KiB
Raw Blame History

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;
forlet i = 0; i <= len; i ++{
//最后循环一次太多次
的console.log字母[I];
}
forlet j = 1; j <len; j ++{
//循环一次太少次并错过索引0处的第一个字符
的console.log字母[J];
}
forlet k = 0; k <len; k ++{
// Goldilocks赞成 - 这是正确的
的console.log字母表[K];
}

Instructions

修复以下函数中的两个索引错误以便将所有数字1到5打印到控制台。

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