|
1 | 1 | function find(str, char) { |
| 2 | + // Start searching from the first character (index 0) |
2 | 3 | let index = 0; |
3 | 4 |
|
| 5 | + // Continue looping while index is less than the length of the string |
| 6 | + // This prevents us from going beyond the last character of the string |
4 | 7 | while (index < str.length) { |
| 8 | + // Check if the current character matches the one we are looking for |
5 | 9 | if (str[index] === char) { |
| 10 | + // If found, return the current index position |
6 | 11 | return index; |
7 | 12 | } |
8 | | - index++; |
| 13 | + // Move to the next character in the string |
| 14 | + index++; // This increments index by 1, so the loop moves through each character |
9 | 15 | } |
| 16 | + |
| 17 | + // If we finish the loop without finding the character, return -1 |
| 18 | + // This means the character does not exist in the string |
10 | 19 | return -1; |
11 | 20 | } |
12 | 21 |
|
13 | | -console.log(find("code your future", "u")); |
14 | | -console.log(find("code your future", "z")); |
15 | | - |
16 | | -// The while loop statement allows us to do iteration - the repetition of a certain number of tasks according to some condition |
17 | | -// See the docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while |
| 22 | +// Test examples: |
| 23 | +console.log(find("code your future", "u")); // Should output the first index of 'u' |
| 24 | +console.log(find("code your future", "z")); // Should output -1 since 'z' is not in the string |
18 | 25 |
|
19 | | -// Use the Python Visualiser to help you play computer with this example and observe how this code is executed |
20 | | -// Pay particular attention to the following: |
| 26 | +/* |
| 27 | +Explanation: |
| 28 | +a) The 'index' variable starts at 0 and increments by 1 each loop (index++), allowing the function to check each character in the string. |
| 29 | +b) The 'if' statement checks whether the current character (str[index]) matches the character we're searching for. |
| 30 | +c) 'index++' is used to move forward to the next character in the string on each loop iteration. |
| 31 | +d) The condition 'index < str.length' ensures the loop only runs while 'index' is a valid position inside the string, preventing errors. |
| 32 | +*/ |
21 | 33 |
|
22 | | -// a) How the index variable updates during the call to find |
23 | | -// b) What is the if statement used to check |
24 | | -// c) Why is index++ being used? |
25 | | -// d) What is the condition index < str.length used for? |
|
0 commit comments