mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-06-28 21:00:56 +08:00
feat(curriculum): Add interactive examples to How Can You Repeat a String x Number of Times (#63230)
This commit is contained in:
parent
3b0c6c5172
commit
d002589aa4
@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-can-you-repeat-a-string-x-number-of-times
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
When working with JavaScript, you may encounter situations where you need to repeat a string a specific number of times.
|
||||
|
||||
@ -19,12 +19,16 @@ string.repeat(count);
|
||||
|
||||
`string` is the string that you want to repeat, and `count` is the number of times you want the string to be repeated. Here's an example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let word = "Hello!";
|
||||
let repeatedWord = word.repeat(3);
|
||||
console.log(repeatedWord); // Output: "Hello!Hello!Hello!"
|
||||
console.log(repeatedWord); // "Hello!Hello!Hello!"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this case, the string `Hello!` is repeated three times, resulting in `Hello!Hello!Hello!`.
|
||||
|
||||
While the `repeat()` method is useful, there are a few exceptions and limitations to keep in mind.
|
||||
@ -47,18 +51,26 @@ console.log(word.repeat(Infinity)); // Throws RangeError: Invalid count value
|
||||
|
||||
If the count is not an integer (such as a decimal like `2.5`), the `repeat()` method will round it down to the nearest integer.
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let word = "Test";
|
||||
console.log(word.repeat(2.5)); // Output: "TestTest"
|
||||
console.log(word.repeat(2.5)); // "TestTest"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
If you pass `0` as the count, the `repeat()` method will return an empty string.
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let word = "Test";
|
||||
console.log(word.repeat(0)); // Output: ""
|
||||
console.log(word.repeat(0)); // ""
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The `repeat()` method can simplify tasks that involve string duplication, making your code more concise and readable.
|
||||
|
||||
Whether you're generating repeated text patterns or filling a space with characters, `repeat()` can save you from writing loops or more complex code.
|
||||
|
||||
Loading…
Reference in New Issue
Block a user