chore(i8n,curriculum): processed translations (#41496)

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
camperbot
2021-03-15 14:01:16 -06:00
committed by GitHub
parent cd722a0e7f
commit dcadc249f4
44 changed files with 492 additions and 450 deletions

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7da9367417b2b2512b67 id: 587d7da9367417b2b2512b67
title: Add Elements to the End of an Array Using concat Instead of push title: 使用 concat 而不是 push 将元素添加到数组的末尾
challengeType: 1 challengeType: 1
forumTopicId: 301226 forumTopicId: 301226
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
@ -8,50 +8,50 @@ dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
# --description-- # --description--
Functional programming is all about creating and using non-mutating functions. 函数式编程就是创建和使用具有不变性的函数。
The last challenge introduced the `concat` method as a way to combine arrays into a new one without mutating the original arrays. Compare `concat` to the `push` method. `Push` adds an item to the end of the same array it is called on, which mutates that array. Here's an example: 上一个挑战介绍了 `concat` 方法,这是一种在不改变原始数组的前提下,将数组组合成新数组的方法。 将 `concat` 方法与 `push` 方法做比较。 `push` 将元素添加到调用它的数组的末尾,这样会改变该数组。 举个例子:
```js ```js
var arr = [1, 2, 3]; var arr = [1, 2, 3];
arr.push([4, 5, 6]); arr.push([4, 5, 6]);
// arr is changed to [1, 2, 3, [4, 5, 6]]
// Not the functional programming way
``` ```
`Concat` offers a way to add new items to the end of an array without any mutating side effects. `arr` 的值被修改为 `[1, 2, 3, [4, 5, 6]]`,这不是函数编程方式。
`concat` 方法可以将新项目添加到数组末尾,而不产生副作用。
# --instructions-- # --instructions--
Change the `nonMutatingPush` function so it uses `concat` to add `newItem` to the end of `original` instead of `push`. The function should return an array. 修改 `nonMutatingPush` 函数,用 `concat` 替代 `push``newItem` 添加到 `original` 末尾。 该函数应返回一个数组。
# --hints-- # --hints--
Your code should use the `concat` method. 应该使用 `concat` 方法。
```js ```js
assert(code.match(/\.concat/g)); assert(code.match(/\.concat/g));
``` ```
Your code should not use the `push` method. 不能使用 `push` 方法。
```js ```js
assert(!code.match(/\.?[\s\S]*?push/g)); assert(!code.match(/\.?[\s\S]*?push/g));
``` ```
The `first` array should not change. 不能改变 `first` 数组。
```js ```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3])); assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
``` ```
The `second` array should not change. 不能改变 `second` 数组。
```js ```js
assert(JSON.stringify(second) === JSON.stringify([4, 5])); assert(JSON.stringify(second) === JSON.stringify([4, 5]));
``` ```
`nonMutatingPush([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`. `nonMutatingPush([1, 2, 3], [4, 5])` 应返回 `[1, 2, 3, 4, 5]`
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7dab367417b2b2512b6d id: 587d7dab367417b2b2512b6d
title: Apply Functional Programming to Convert Strings to URL Slugs title: 应用函数式编程将字符串转换为URL片段
challengeType: 1 challengeType: 1
forumTopicId: 301227 forumTopicId: 301227
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
@ -8,45 +8,45 @@ dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
# --description-- # --description--
The last several challenges covered a number of useful array and string methods that follow functional programming principles. We've also learned about `reduce`, which is a powerful method used to reduce problems to simpler forms. From computing averages to sorting, any array operation can be achieved by applying it. Recall that `map` and `filter` are special cases of `reduce`. 最后几个挑战中涵盖了许多符合函数式编程原则并在处理数组和字符串中非常有用的方法。 我们还学习了强大的、可以将问题简化为更简单形式的 `reduce` 方法。 从计算平均值到排序,任何数组操作都可以用它来实现。 回想一下,`map` `filter` 方法都是 `reduce` 的特殊实现。
Let's combine what we've learned to solve a practical problem. 让我们把学到的知识结合起来解决一个实际问题。
Many content management sites (CMS) have the titles of a post added to part of the URL for simple bookmarking purposes. For example, if you write a Medium post titled "Stop Using Reduce", it's likely the URL would have some form of the title string in it (".../stop-using-reduce"). You may have already noticed this on the freeCodeCamp site. 许多内容管理站点CMS为了让添加书签更简单会将帖子的标题添加到 URL 上。 举个例子,如果你写了一篇标题为 `Stop Using Reduce` 的帖子URL很可能会包含标题字符串的某种形式 (如:`.../stop-using-reduce`)。 你可能已经在 freeCodeCamp 网站上注意到了这一点。
# --instructions-- # --instructions--
Fill in the `urlSlug` function so it converts a string `title` and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use `replace`. Here are the requirements: 填写 `urlSlug` 函数,将字符串 `title` 转换成带有连字符号的 URL。 您可以使用本节中介绍的任何方法,但不要用 `replace` 方法。 以下是本次挑战的要求:
The input is a string with spaces and title-cased words 输入包含空格和标题大小写单词的字符串
The output is a string with the spaces between words replaced by a hyphen (`-`) 输出字符串,单词之间的空格用连字符 (`-`) 替换
The output should be all lower-cased letters 输出应该是小写字母
The output should not have any spaces 输出不应有任何空格
# --hints-- # --hints--
Your code should not use the `replace` method for this challenge. 不能使用 `replace` 方法。
```js ```js
assert(!code.match(/\.?[\s\S]*?replace/g)); assert(!code.match(/\.?[\s\S]*?replace/g));
``` ```
`urlSlug("Winter Is Coming")` should return `"winter-is-coming"`. `urlSlug("Winter Is Coming")` 应返回 `winter-is-coming`
```js ```js
assert(urlSlug('Winter Is Coming') === 'winter-is-coming'); assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
``` ```
`urlSlug(" Winter Is Coming")` should return `"winter-is-coming"`. `urlSlug(" Winter Is Coming")` 应返回 `winter-is-coming`
```js ```js
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming'); assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
``` ```
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` should return `"a-mind-needs-books-like-a-sword-needs-a-whetstone"`. `urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` 应返回 `a-mind-needs-books-like-a-sword-needs-a-whetstone`
```js ```js
assert( assert(
@ -55,7 +55,7 @@ assert(
); );
``` ```
`urlSlug("Hold The Door")` should return `"hold-the-door"`. `urlSlug("Hold The Door")` 应返回 `hold-the-door`
```js ```js
assert(urlSlug('Hold The Door') === 'hold-the-door'); assert(urlSlug('Hold The Door') === 'hold-the-door');

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7daa367417b2b2512b6c id: 587d7daa367417b2b2512b6c
title: Combine an Array into a String Using the join Method title: 使用 join 方法将数组组合成字符串
challengeType: 1 challengeType: 1
forumTopicId: 18221 forumTopicId: 18221
dashedName: combine-an-array-into-a-string-using-the-join-method dashedName: combine-an-array-into-a-string-using-the-join-method
@ -8,47 +8,47 @@ dashedName: combine-an-array-into-a-string-using-the-join-method
# --description-- # --description--
The `join` method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string. `join` 方法用来把数组中的所有元素放入一个字符串。 并通过指定的分隔符参数进行分隔。
Here's an example: 举个例子:
```js ```js
var arr = ["Hello", "World"]; var arr = ["Hello", "World"];
var str = arr.join(" "); var str = arr.join(" ");
// Sets str to "Hello World"
``` ```
`str` 的值应该是字符串 `Hello World`
# --instructions-- # --instructions--
Use the `join` method (among others) inside the `sentensify` function to make a sentence from the words in the string `str`. The function should return a string. For example, "I-like-Star-Wars" would be converted to "I like Star Wars". For this challenge, do not use the `replace` method. 在函数 `sentensify` 内用 `join` 方法(及其他方法)用字符串 `str` 中的单词造句,这个函数应返回一个字符串。 该函数应返回一个数组。 举个例子,`I-like-Star-Wars` 会被转换成 `I like Star Wars`。 在此挑战中请勿使用 `replace` 方法。
# --hints-- # --hints--
Your code should use the `join` method. 应使用 `join` 方法。
```js ```js
assert(code.match(/\.join/g)); assert(code.match(/\.join/g));
``` ```
Your code should not use the `replace` method. 不能使用 `replace` 方法。
```js ```js
assert(!code.match(/\.?[\s\S]*?replace/g)); assert(!code.match(/\.?[\s\S]*?replace/g));
``` ```
`sentensify("May-the-force-be-with-you")` should return a string. `sentensify("May-the-force-be-with-you")` 应返回一个字符串。
```js ```js
assert(typeof sentensify('May-the-force-be-with-you') === 'string'); assert(typeof sentensify('May-the-force-be-with-you') === 'string');
``` ```
`sentensify("May-the-force-be-with-you")` should return `"May the force be with you"`. `sentensify("May-the-force-be-with-you")` 应返回 `May the force be with you`
```js ```js
assert(sentensify('May-the-force-be-with-you') === 'May the force be with you'); assert(sentensify('May-the-force-be-with-you') === 'May the force be with you');
``` ```
`sentensify("The.force.is.strong.with.this.one")` should return `"The force is strong with this one"`. `sentensify("The.force.is.strong.with.this.one")` 应返回 `The force is strong with this one`
```js ```js
assert( assert(
@ -57,7 +57,7 @@ assert(
); );
``` ```
`sentensify("There,has,been,an,awakening")` should return `"There has been an awakening"`. `sentensify("There,has,been,an,awakening")` 应返回 `There has been an awakening`
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7da9367417b2b2512b66 id: 587d7da9367417b2b2512b66
title: Combine Two Arrays Using the concat Method title: 使用 concat 方法组合两个数组
challengeType: 1 challengeType: 1
forumTopicId: 301229 forumTopicId: 301229
dashedName: combine-two-arrays-using-the-concat-method dashedName: combine-two-arrays-using-the-concat-method
@ -8,38 +8,39 @@ dashedName: combine-two-arrays-using-the-concat-method
# --description-- # --description--
<dfn>Concatenation</dfn> means to join items end to end. JavaScript offers the `concat` method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to `concat`, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. Here's an example: <dfn>Concatenation</dfn> 意思是将元素连接到尾部。 同理JavaScript 为字符串和数组提供了`concat`方法。 对数组来说,在一个数组上调用 `concat` 方法,然后提供另一个数组作为参数添加到第一个数组末尾。 它返回一个新数组,不会改变任何一个原始数组。 举个例子:
```js ```js
[1, 2, 3].concat([4, 5, 6]); [1, 2, 3].concat([4, 5, 6]);
// Returns a new array [1, 2, 3, 4, 5, 6]
``` ```
返回的数组将是 `[1, 2, 3, 4, 5, 6]`
# --instructions-- # --instructions--
Use the `concat` method in the `nonMutatingConcat` function to concatenate `attach` to the end of `original`. The function should return the concatenated array. `nonMutatingConcat` 函数里使用 `concat`,将 `attach` 拼接到 `original` 尾部。 函数返回拼接后的数组。
# --hints-- # --hints--
Your code should use the `concat` method. 应该使用 `concat` 方法。
```js ```js
assert(code.match(/\.concat/g)); assert(code.match(/\.concat/g));
``` ```
The `first` array should not change. 不应该改变 `first` 数组。
```js ```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3])); assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
``` ```
The `second` array should not change. 不应该改变 `second` 数组。
```js ```js
assert(JSON.stringify(second) === JSON.stringify([4, 5])); assert(JSON.stringify(second) === JSON.stringify([4, 5]));
``` ```
`nonMutatingConcat([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`. `nonMutatingConcat([1, 2, 3], [4, 5])` 应该返回 `[1, 2, 3, 4, 5]`
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7dab367417b2b2512b70 id: 587d7dab367417b2b2512b70
title: 函数柯里化 title: 函数柯里化和局部调用
challengeType: 1 challengeType: 1
forumTopicId: 301232 forumTopicId: 301232
dashedName: introduction-to-currying-and-partial-application dashedName: introduction-to-currying-and-partial-application
@ -8,7 +8,7 @@ dashedName: introduction-to-currying-and-partial-application
# --description-- # --description--
<dfn>arity</dfn> 是函数所需的形参的数量。 函数柯里化(<dfn>Currying</dfn>)意思是把接受多个 arity 的函数变换成接受单一arity 的函数。 <dfn>arity</dfn>(参数个数)是函数所需的形参的数量。 函数柯里化(<dfn>Currying</dfn>)意思是把接受多个 arity 的函数变换成接受单一 arity 的函数。
换句话说,就是重构函数让它接收一个参数,然后返回接收下一个参数的函数,依此类推。 换句话说,就是重构函数让它接收一个参数,然后返回接收下一个参数的函数,依此类推。

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b8e367417b2b2512b5f id: 587d7b8e367417b2b2512b5f
title: Pass Arguments to Avoid External Dependence in a Function title: 传递参数以避免函数中的外部依赖
challengeType: 1 challengeType: 1
forumTopicId: 301234 forumTopicId: 301234
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
@ -8,39 +8,39 @@ dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
# --description-- # --description--
The last challenge was a step closer to functional programming principles, but there is still something missing. 上一个挑战是更接近函数式编程原则的挑战,但是仍然缺少一些东西。
We didn't alter the global variable value, but the function `incrementer` would not work without the global variable `fixedValue` being there. 虽然我们没有改变全局变量值,但在没有全局变量 `fixedValue` 的情况下,`incrementer` 函数将不起作用。
Another principle of functional programming is to always declare your dependencies explicitly. This means if a function depends on a variable or object being present, then pass that variable or object directly into the function as an argument. 函数式编程的另一个原则是:总是显式声明依赖关系。 如果函数依赖于一个变量或对象,那么将该变量或对象作为参数直接传递到函数中。
There are several good consequences from this principle. The function is easier to test, you know exactly what input it takes, and it won't depend on anything else in your program. 这样做会有很多好处。 其中一点是让函数更容易测试,因为你确切地知道参数是什么,并且这个参数也不依赖于程序中的任何其他内容。
This can give you more confidence when you alter, remove, or add new code. You would know what you can or cannot change and you can see where the potential traps are. 其次,这样做可以让你更加自信地更改,删除或添加新代码。 因为你很清楚哪些是可以改的,哪些是不可以改的,这样你就知道哪里可能会有潜在的陷阱。
Finally, the function would always produce the same output for the same set of inputs, no matter what part of the code executes it. 最后,无论代码的哪一部分执行它,函数总是会为同一组输入生成相同的输出。
# --instructions-- # --instructions--
Let's update the `incrementer` function to clearly declare its dependencies. 更新 `incrementer` 函数,明确声明其依赖项。
Write the `incrementer` function so it takes an argument, and then returns a result after increasing the value by one. 编写 `incrementer` 函数,获取它的参数,然后将值增加 1。
# --hints-- # --hints--
Your function `incrementer` should not change the value of `fixedValue` (which is `4`). `incrementer` 函数不能修改 `fixedValue` 的值(它的值是 `4`)。
```js ```js
assert(fixedValue === 4); assert(fixedValue === 4);
``` ```
Your `incrementer` function should take an argument. `incrementer` 函数应该接收一个参数。
```js ```js
assert(incrementer.length === 1); assert(incrementer.length === 1);
``` ```
Your `incrementer` function should return a value that is one larger than the `fixedValue` value. `incrementer` 函数应返回比 `fixedValue` 更大的值。
```js ```js
const __newValue = incrementer(fixedValue); const __newValue = incrementer(fixedValue);

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7da9367417b2b2512b6a id: 587d7da9367417b2b2512b6a
title: Return a Sorted Array Without Changing the Original Array title: 在不更改原始数组的前提下返回排序后的数组
challengeType: 1 challengeType: 1
forumTopicId: 301237 forumTopicId: 301237
dashedName: return-a-sorted-array-without-changing-the-original-array dashedName: return-a-sorted-array-without-changing-the-original-array
@ -8,27 +8,27 @@ dashedName: return-a-sorted-array-without-changing-the-original-array
# --description-- # --description--
A side effect of the `sort` method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that `slice` and `concat` return a new array), then run the `sort` method. `sort` 方法会产生改变原始数组中元素顺序的副作用。 换句话说,它会改变数组的位置。 避免这种情况的一种方法是先将空数组连接到正在排序的数组上(记住 `slice` `concat` 返回一个新数组),再用`sort`方法。
# --instructions-- # --instructions--
Use the `sort` method in the `nonMutatingSort` function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the `globalArray` variable. `nonMutatingSort` 函数中使用 `sort` 方法对数组中的元素按升序进行排列。 函数不能改变 `globalArray` 变量,应返回一个新数组。
# --hints-- # --hints--
Your code should use the `sort` method. 应该使用 `sort` 方法。
```js ```js
assert(nonMutatingSort.toString().match(/\.sort/g)); assert(nonMutatingSort.toString().match(/\.sort/g));
``` ```
The `globalArray` variable should not change. `globalArray` 变量不应该改变。
```js ```js
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9])); assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
``` ```
`nonMutatingSort(globalArray)` should return `[2, 3, 5, 6, 9]`. `nonMutatingSort(globalArray)` 应该返回 `[2, 3, 5, 6, 9]`
```js ```js
assert( assert(
@ -37,18 +37,32 @@ assert(
); );
``` ```
`nonMutatingSort(globalArray)` should not be hard coded. `nonMutatingSort(globalArray)` 不应被硬编码。
```js ```js
assert(!nonMutatingSort.toString().match(/[23569]/g)); assert(!nonMutatingSort.toString().match(/[23569]/g));
``` ```
The function should return a new array, not the array passed to it. 函数应该返回一个新数组,而不是传递给它的数组。
```js ```js
assert(nonMutatingSort(globalArray) !== globalArray); assert(nonMutatingSort(globalArray) !== globalArray);
``` ```
`nonMutatingSort([1, 30, 4, 21, 100000])` 应该返回 `[1, 4, 21, 30, 100000]`
```js
assert(JSON.stringify(nonMutatingSort([1, 30, 4, 21, 100000])) ===
JSON.stringify([1, 4, 21, 30, 100000]))
```
`nonMutatingSort([140000, 104, 99])` 应该返回 `[99, 104, 140000]`
```js
assert(JSON.stringify(nonMutatingSort([140000, 104, 99])) ===
JSON.stringify([99, 104, 140000]))
```
# --seed-- # --seed--
## --seed-contents-- ## --seed-contents--

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7da9367417b2b2512b69 id: 587d7da9367417b2b2512b69
title: Sort an Array Alphabetically using the sort Method title: 使用 sort 方法按字母顺序给数组排序
challengeType: 1 challengeType: 1
forumTopicId: 18303 forumTopicId: 18303
dashedName: sort-an-array-alphabetically-using-the-sort-method dashedName: sort-an-array-alphabetically-using-the-sort-method
@ -8,9 +8,9 @@ dashedName: sort-an-array-alphabetically-using-the-sort-method
# --description-- # --description--
The `sort` method sorts the elements of an array according to the callback function. `sort` 方法可以根据回调函数对数组元素进行排序。
For example: 举个例子:
```js ```js
function ascendingOrder(arr) { function ascendingOrder(arr) {
@ -19,32 +19,36 @@ function ascendingOrder(arr) {
}); });
} }
ascendingOrder([1, 5, 2, 3, 4]); ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5] ```
这将返回值 `[1, 2, 3, 4, 5]`
```js
function reverseAlpha(arr) { function reverseAlpha(arr) {
return arr.sort(function(a, b) { return arr.sort(function(a, b) {
return a === b ? 0 : a < b ? 1 : -1; return a === b ? 0 : a < b ? 1 : -1;
}); });
} }
reverseAlpha(['l', 'h', 'z', 'b', 's']); reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
``` ```
JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items. When such a callback function, normally called `compareFunction`, is supplied, the array elements are sorted according to the return value of the `compareFunction`: If `compareFunction(a,b)` returns a value less than 0 for two elements `a` and `b`, then `a` will come before `b`. If `compareFunction(a,b)` returns a value greater than 0 for two elements `a` and `b`, then `b` will come before `a`. If `compareFunction(a,b)` returns a value equal to 0 for two elements `a` and `b`, then `a` and `b` will remain unchanged. 这将返回值 `['z', 's', 'l', 'h', 'b']`
JavaScript 的默认排序方法是 Unicode 值顺序排序,有时可能会得到意想不到的结果。 因此,建议提供一个回调函数来指定如何对数组项目排序。 这个回调函数通常叫做 `compareFunction`,它根据 `compareFunction` 的返回值决定数组元素的排序方式: 如果两个元素 `a``b``compareFunction(a,b)` 返回一个比 0 小的值,那么 `a` 会在 `b` 的前面。 如果两个元素 `a``b``compareFunction(a,b)` 返回一个比 0 大的值,那么 `b` 会在 `a` 的前面。 如果两个元素 `a``b``compareFunction(a,b)` 返回等于 0 的值,那么 `a``b` 的位置保持不变。
# --instructions-- # --instructions--
Use the `sort` method in the `alphabeticalOrder` function to sort the elements of `arr` in alphabetical order. `alphabeticalOrder` 函数中使用 `sort` 方法对 `arr` 中的元素按照字母顺序排列。
# --hints-- # --hints--
Your code should use the `sort` method. 应该使用 `sort` 方法。
```js ```js
assert(code.match(/\.sort/g)); assert(code.match(/\.sort/g));
``` ```
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` should return `["a", "a", "c", "d", "g", "z"]`. `alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` 应返回 `["a", "a", "c", "d", "g", "z"]`
```js ```js
assert( assert(
@ -53,7 +57,7 @@ assert(
); );
``` ```
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` should return `["a", "h", "m", "m", "n", "x"]`. `alphabeticalOrder(["x", "h", "a", "m", "n", "m"])`应返回`["a", "h", "m", "m", "n", "x"]`
```js ```js
assert( assert(
@ -62,7 +66,7 @@ assert(
); );
``` ```
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` should return `["a", "a", "a", "a", "t", "x"]`. `alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` 应返回 `["a", "a", "a", "a", "t", "x"]`
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7daa367417b2b2512b6b id: 587d7daa367417b2b2512b6b
title: Split a String into an Array Using the split Method title: 使用 split 方法将字符串拆分成数组
challengeType: 1 challengeType: 1
forumTopicId: 18305 forumTopicId: 18305
dashedName: split-a-string-into-an-array-using-the-split-method dashedName: split-a-string-into-an-array-using-the-split-method
@ -8,35 +8,35 @@ dashedName: split-a-string-into-an-array-using-the-split-method
# --description-- # --description--
The `split` method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string. `split` 方法将一个字符串分割成一个字符串数组。 它需要一个参数作为分隔符,它可以是用于拆分字符串或正则表达式的一个字符。 举个例子,如果分隔符是空格,你会得到一个单词数组;如果分隔符是空字符串,你会得到一个由字符串中每个字符组成的数组。
Here are two examples that split one string by spaces, then another by digits using a regular expression: 下面是两个用空格分隔一个字符串的例子,另一个是用数字的正则表达式分隔:
```js ```js
var str = "Hello World"; var str = "Hello World";
var bySpace = str.split(" "); var bySpace = str.split(" ");
// Sets bySpace to ["Hello", "World"]
var otherString = "How9are7you2today"; var otherString = "How9are7you2today";
var byDigits = otherString.split(/\d/); var byDigits = otherString.split(/\d/);
// Sets byDigits to ["How", "are", "you", "today"]
``` ```
Since strings are immutable, the `split` method makes it easier to work with them. `bySpace` 将有值 `["Hello", "World"]``byDigits` 将有值 `["How", "are", "you", "today"]`
因为字符串是不可变的,`split` 方法操作它们更方便。
# --instructions-- # --instructions--
Use the `split` method inside the `splitify` function to split `str` into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation. `splitify` 函数中用 `split` 方法将 `str` 分割成单词数组。 这个方法应该返回一个数组。 单词不一定都是用空格分隔,所以数组中不应包含标点符号。
# --hints-- # --hints--
Your code should use the `split` method. 应该使用 `split` 方法。
```js ```js
assert(code.match(/\.split/g)); assert(code.match(/\.split/g));
``` ```
`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`. `splitify("Hello World,I-am code")` 应返回 `["Hello", "World", "I", "am", "code"]`
```js ```js
assert( assert(
@ -45,7 +45,7 @@ assert(
); );
``` ```
`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`. `splitify("Earth-is-our home")` 应返回 `["Earth", "is", "our", "home"]`
```js ```js
assert( assert(
@ -54,7 +54,7 @@ assert(
); );
``` ```
`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`. `splitify("This.is.a-sentence")` 应返回 `["This", "is", "a", "sentence"]`
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b8e367417b2b2512b5c id: 587d7b8e367417b2b2512b5c
title: Understand Functional Programming Terminology title: 了解函数式编程术语
challengeType: 1 challengeType: 1
forumTopicId: 301240 forumTopicId: 301240
dashedName: understand-functional-programming-terminology dashedName: understand-functional-programming-terminology
@ -8,47 +8,47 @@ dashedName: understand-functional-programming-terminology
# --description-- # --description--
The FCC Team had a mood swing and now wants two types of tea: green tea and black tea. General Fact: Client mood swings are pretty common. FCC 团队需求有变更,现在想要两种茶:绿茶(green tea)和红茶(black tea)。 事实证明,用户需求变更是很常见的。
With that information, we'll need to revisit the `getTea` function from last challenge to handle various tea requests. We can modify `getTea` to accept a function as a parameter to be able to change the type of tea it prepares. This makes `getTea` more flexible, and gives the programmer more control when client requests change. 基于以上信息,我们需要重构上一节挑战中的 `getTea` 函数来处理多种茶的请求。 我们可以修改 `getTea` 接受一个函数作为参数,使它能够修改茶的类型。 这让 `getTea` 更灵活,也使需求变更时为程序员提供更多控制权。
But first, let's cover some functional terminology: 首先,我们将介绍一些术语:
<dfn>Callbacks</dfn> are the functions that are slipped or passed into another function to decide the invocation of that function. You may have seen them passed to other methods, for example in `filter`, the callback function tells JavaScript the criteria for how to filter an array. <dfn>Callbacks</dfn> 是被传递到另一个函数中调用的函数。 你应该已经在其他函数中看过这个写法,例如在 `filter` 中,回调函数告诉 JavaScript 以什么规则过滤数组。
Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called <dfn>first class</dfn> functions. In JavaScript, all functions are first class functions. 函数就像其他正常值一样,可以赋值给变量、传递给另一个函数,或从其它函数返回,这种函数叫做头等 <dfn>first class</dfn> 函数。 在 JavaScript 中,所有函数都是头等函数。
The functions that take a function as an argument, or return a function as a return value are called <dfn>higher order</dfn> functions. 将函数为参数或返回值的函数叫做高阶 ( <dfn>higher order</dfn>) 函数。
When the functions are passed in to another function or returned from another function, then those functions which gets passed in or returned can be called a <dfn>lambda</dfn>. 当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以叫做<dfn>lambda</dfn>
# --instructions-- # --instructions--
Prepare 27 cups of green tea and 13 cups of black tea and store them in `tea4GreenTeamFCC` and `tea4BlackTeamFCC` variables, respectively. Note that the `getTea` function has been modified so it now takes a function as the first argument. 准备 27 杯绿茶和 13 杯红茶,分别存入 `tea4GreenTeamFCC` `tea4BlackTeamFCC` 变量。 请注意,`getTea` 函数已经变了,现在它接收一个函数作为第一个参数。
Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons. 注意:数据(茶的数量)作为最后一个参数。 我们将在后面的课程中对此进行更多讨论。
# --hints-- # --hints--
The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team. `tea4GreenTeamFCC` 变量应存有为团队准备的 27 杯茶。
```js ```js
assert(tea4GreenTeamFCC.length === 27); assert(tea4GreenTeamFCC.length === 27);
``` ```
The `tea4GreenTeamFCC` variable should hold cups of green tea. `tea4GreenTeamFCC` 变量应存有绿茶。
```js ```js
assert(tea4GreenTeamFCC[0] === 'greenTea'); assert(tea4GreenTeamFCC[0] === 'greenTea');
``` ```
The `tea4BlackTeamFCC` variable should hold 13 cups of black tea. `tea4BlackTeamFCC` 变量应存有 13 杯红茶。
```js ```js
assert(tea4BlackTeamFCC.length === 13); assert(tea4BlackTeamFCC.length === 13);
``` ```
The `tea4BlackTeamFCC` variable should hold cups of black tea. `tea4BlackTeamFCC` 变量应存有红茶。
```js ```js
assert(tea4BlackTeamFCC[0] === 'blackTea'); assert(tea4BlackTeamFCC[0] === 'blackTea');

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b8e367417b2b2512b5d id: 587d7b8e367417b2b2512b5d
title: Understand the Hazards of Using Imperative Code title: 了解使用命令式编程的危害
challengeType: 1 challengeType: 1
forumTopicId: 301241 forumTopicId: 301241
dashedName: understand-the-hazards-of-using-imperative-code dashedName: understand-the-hazards-of-using-imperative-code
@ -8,31 +8,31 @@ dashedName: understand-the-hazards-of-using-imperative-code
# --description-- # --description--
Functional programming is a good habit. It keeps your code easy to manage, and saves you from sneaky bugs. But before we get there, let's look at an imperative approach to programming to highlight where you may have issues. 使用函数式编程是一个好的习惯。 它使你的代码易于管理,避免潜在的 bug。 但在开始之前,先看看命令式编程方法,以强调你可能有什么问题。
In English (and many other languages), the imperative tense is used to give commands. Similarly, an imperative style in programming is one that gives the computer a set of statements to perform a task. 在英语 (以及许多其他语言) 中,命令式时态用来发出指令。 同样,命令式编程是向计算机提供一套执行任务的声明。
Often the statements change the state of the program, like updating global variables. A classic example is writing a `for` loop that gives exact directions to iterate over the indices of an array. 命令式编程常常改变程序状态,例如更新全局变量。 一个典型的例子是编写 `for` 循环,它为一个数组的索引提供了准确的迭代方向。
In contrast, functional programming is a form of declarative programming. You tell the computer what you want done by calling a method or function. 相反,函数式编程是声明式编程的一种形式。 通过调用方法或函数来告诉计算机要做什么。
JavaScript offers many predefined methods that handle common tasks so you don't need to write out how the computer should perform them. For example, instead of using the `for` loop mentioned above, you could call the `map` method which handles the details of iterating over an array. This helps to avoid semantic errors, like the "Off By One Errors" that were covered in the Debugging section. JavaScript 提供了许多处理常见任务的方法,所以你无需写出计算机应如何执行它们。 例如,你可以用 `map` 函数替代上面提到的 `for` 循环来处理数组迭代。 这有助于避免语义错误,如调试章节介绍的 "Off By One Errors"。
Consider the scenario: you are browsing the web in your browser, and want to track the tabs you have opened. Let's try to model this using some simple object-oriented code. 考虑这样的场景:你正在浏览器中浏览网页,并想操作你打开的标签。 下面我们来试试用面向对象的思路来描述这种情景。
A Window object is made up of tabs, and you usually have more than one Window open. The titles of each open site in each Window object is held in an array. After working in the browser (opening new tabs, merging windows, and closing tabs), you want to print the tabs that are still open. Closed tabs are removed from the array and new tabs (for simplicity) get added to the end of it. 窗口对象由选项卡组成,通常会打开多个窗口。 窗口对象中每个打开网站的标题都保存在一个数组中。 在对浏览器进行了如打开新标签、合并窗口、关闭标签之类的操作后,你需要输出所有打开的标签。 关掉的标签将从数组中删除,新打开的标签(为简单起见)则添加到数组的末尾。
The code editor shows an implementation of this functionality with functions for `tabOpen()`, `tabClose()`, and `join()`. The array `tabs` is part of the Window object that stores the name of the open pages. 代码编辑器中显示了此功能的实现,其中包含 `tabOpen()``tabClose()`,和 `join()` 函数。 `tabs` 数组是窗口对象的一部分用于储存打开页面的名称。
# --instructions-- # --instructions--
Examine the code in the editor. It's using a method that has side effects in the program, causing incorrect behaviour. The final list of open tabs, stored in `finalTabs.tabs`, should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` but the list produced by the code is slightly different. 在编辑器中运行代码。 它使用了有副作用的方法,导致输出错误。 存储在 `finalTabs.tabs` 中的打开标签的最终列表应该是 `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`,但输出会略有不同。
Change `Window.prototype.tabClose` so that it removes the correct tab. 修改 `Window.prototype.tabClose` 使其删除正确的标签。
# --hints-- # --hints--
`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` `finalTabs.tabs` 应该是 `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
```js ```js
assert.deepEqual(finalTabs.tabs, [ assert.deepEqual(finalTabs.tabs, [

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b88367417b2b2512b45 id: 587d7b88367417b2b2512b45
title: 'Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem' title: '使用高阶函数 mapfilter 或者 reduce 来解决复杂问题'
challengeType: 1 challengeType: 1
forumTopicId: 301311 forumTopicId: 301311
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
@ -8,30 +8,30 @@ dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-p
# --description-- # --description--
Now that you have worked through a few challenges using higher-order functions like `map()`, `filter()`, and `reduce()`, you now get to apply them to solve a more complex challenge. 已经接触了高阶函数如 `map()` `filter()` `reduce()`的使用,是时候用它们来完成一些复杂的挑战了。
# --instructions-- # --instructions--
We have defined a function named `squareList`. You need to complete the code for the `squareList` function using any combination of `map()`, `filter()`, and `reduce()` so that it returns a new array containing only the square of *only* the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array containing only real numbers is `[-3, 4.8, 5, 3, -3.2]`. 已经定义了一个函数 `squareList`。 你需要使用 `map()``filter()` `reduce()` 的任意组合来完成 `squareList` 函数的代码。当传入一个实数数组时,返回一个*仅*包含正整数(小数不是整数)的平方的新数组。 仅包含实数字的数组示例是 `[-3, 4.8, 5, 3, -3.2]`
**Note:** Your function should not use any kind of `for` or `while` loops or the `forEach()` function. **注意:** 函数不应该包含任何形式的 `for` 或者 `while` 循环或者 `forEach()` 函数。
# --hints-- # --hints--
`squareList` should be a `function`. `squareList` 应该是一个 `function`
```js ```js
assert.typeOf(squareList, 'function'), assert.typeOf(squareList, 'function'),
'<code>squareList</code> should be a <code>function</code>'; '<code>squareList</code> should be a <code>function</code>';
``` ```
`for`, `while`, and `forEach` should not be used. 不应该使用 `for``while` 或者 `forEach`
```js ```js
assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g)); assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g));
``` ```
`map`, `filter`, or `reduce` should be used. 应该使用 `map``filter` 或者 `reduce`
```js ```js
assert( assert(
@ -41,13 +41,13 @@ assert(
); );
``` ```
The function should return an `array`. 函数应该返回 `array`
```js ```js
assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]))); assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
``` ```
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` should return `[16, 1764, 36]`. `squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` 应该返回 `[16, 1764, 36]`
```js ```js
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [ assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
@ -57,7 +57,7 @@ assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
]); ]);
``` ```
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` should return `[9, 100, 49]`. `squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` 应该返回 `[9, 100, 49]`
```js ```js
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [ assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7dab367417b2b2512b6e id: 587d7dab367417b2b2512b6e
title: Use the every Method to Check that Every Element in an Array Meets a Criteria title: 使用 every 方法检查数组中的每个元素是否符合条件
challengeType: 1 challengeType: 1
forumTopicId: 301312 forumTopicId: 301312
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
@ -8,43 +8,44 @@ dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a
# --description-- # --description--
The `every` method works with arrays to check if *every* element passes a particular test. It returns a Boolean value - `true` if all values meet the criteria, `false` if not. `every` 方法用于检测数组中*所有*元素是否都符合指定条件。 如果所有元素满足条件,返回布尔值 `true`,反之返回 `false`
For example, the following code would check if every element in the `numbers` array is less than 10: 举个例子,下面的代码检测数组 `numbers` 的所有元素是否都小于 10
```js ```js
var numbers = [1, 5, 8, 0, 10, 11]; var numbers = [1, 5, 8, 0, 10, 11];
numbers.every(function(currentValue) { numbers.every(function(currentValue) {
return currentValue < 10; return currentValue < 10;
}); });
// Returns false
``` ```
`every` 方法在这里会返回 `false`
# --instructions-- # --instructions--
Use the `every` method inside the `checkPositive` function to check if every element in `arr` is positive. The function should return a Boolean value. `checkPositive` 函数中使用 `every` 方法检查 `arr` 中是否所有元素都是正数。 函数应返回一个布尔值。
# --hints-- # --hints--
Your code should use the `every` method. 应使用`every`方法。
```js ```js
assert(code.match(/\.every/g)); assert(code.match(/\.every/g));
``` ```
`checkPositive([1, 2, 3, -4, 5])` should return `false`. `checkPositive([1, 2, 3, -4, 5])` 应返回 `false`
```js ```js
assert.isFalse(checkPositive([1, 2, 3, -4, 5])); assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
``` ```
`checkPositive([1, 2, 3, 4, 5])` should return `true`. `checkPositive([1, 2, 3, 4, 5])` 应返回 `true`
```js ```js
assert.isTrue(checkPositive([1, 2, 3, 4, 5])); assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
``` ```
`checkPositive([1, -2, 3, -4, 5])` should return `false`. `checkPositive([1, -2, 3, -4, 5])` 应返回 `false`
```js ```js
assert.isFalse(checkPositive([1, -2, 3, -4, 5])); assert.isFalse(checkPositive([1, -2, 3, -4, 5]));

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b8f367417b2b2512b63 id: 587d7b8f367417b2b2512b63
title: Use the filter Method to Extract Data from an Array title: 使用 filter 方法从数组中提取数据
challengeType: 1 challengeType: 1
forumTopicId: 18179 forumTopicId: 18179
dashedName: use-the-filter-method-to-extract-data-from-an-array dashedName: use-the-filter-method-to-extract-data-from-an-array
@ -8,13 +8,13 @@ dashedName: use-the-filter-method-to-extract-data-from-an-array
# --description-- # --description--
Another useful array function is `Array.prototype.filter()`, or simply `filter()`. 另一个有用的数组方法是 `filter()`(即 `Array.prototype.filter()`)。
`filter` calls a function on each element of an array and returns a new array containing only the elements for which that function returns `true`. In other words, it filters the array, based on the function passed to it. Like `map`, it does this without needing to modify the original array. `filter` 接收一个回调函数,将回调函数内的逻辑应用于数组的每个元素,新数组包含根据回调函数内条件返回 `true` 的元素。 换言之,它根据传递给它的函数过滤数组。 和 `map` 一样filter 不会改变原始数组。
The callback function accepts three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `filter` method was called. 回调函数接收三个参数。 第一个参数是当前正在被处理的元素。 第二个参数是这个元素的索引,第三个参数是在其上调用 `filter` 方法的数组。
See below for an example using the `filter` method on the `users` array to return a new array containing only the users under the age of 30. For simplicity, the example only uses the first argument of the callback. 看下在 `users` 上使用 `filter` 方法的例子,返回了一个包含了 30 岁以下的用户新数组。 为了简化,例子里只使用了回调函数的第一个参数。
```js ```js
const users = [ const users = [
@ -24,16 +24,18 @@ const users = [
]; ];
const usersUnder30 = users.filter(user => user.age < 30); const usersUnder30 = users.filter(user => user.age < 30);
console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ] console.log(usersUnder30);
``` ```
控制台将显示值 `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`
# --instructions-- # --instructions--
The variable `watchList` holds an array of objects with information on several movies. Use a combination of `filter` and `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys. The new array should only include objects where `imdbRating` is greater than or equal to 8.0. Note that the rating values are saved as strings in the object and you may need to convert them into numbers to perform mathematical operations on them. `watchList` 变量中包含一组存有多部电影信息对象。 结合 `filter` `map` 返回一个 `watchList` 只包含 `title` `rating` 属性的新数组。 新数组只包含 `imdbRating` 值大于或等于 8.0 的对象。 请注意,`rating` 值在对象中保存为字符串,你可能需要将它转换成数字来执行运算。
# --hints-- # --hints--
The `watchList` variable should not change. `watchList`应保持不变。
```js ```js
assert( assert(
@ -41,19 +43,19 @@ assert(
); );
``` ```
Your code should use the `filter` method. 应使用 `filter` 方法。
```js ```js
assert(code.match(/\.filter/g)); assert(code.match(/\.filter/g));
``` ```
Your code should not use a `for` loop. 不能使用 `for` 循环。
```js ```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g)); assert(!code.match(/for\s*?\([\s\S]*?\)/g));
``` ```
`filteredList` should equal `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`. `filteredList` 应等于 `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`
```js ```js
assert.deepEqual(filteredList, [ assert.deepEqual(filteredList, [

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b8f367417b2b2512b61 id: 587d7b8f367417b2b2512b61
title: Use the map Method to Extract Data from an Array title: 使用 map 方法从数组中提取数据
challengeType: 1 challengeType: 1
forumTopicId: 18214 forumTopicId: 18214
dashedName: use-the-map-method-to-extract-data-from-an-array dashedName: use-the-map-method-to-extract-data-from-an-array
@ -8,19 +8,19 @@ dashedName: use-the-map-method-to-extract-data-from-an-array
# --description-- # --description--
So far we have learned to use pure functions to avoid side effects in a program. Also, we have seen the value in having a function only depend on its input arguments. 目前为止,我们已经学会了使用纯函数来避免程序中的副作用。 此外,我们已经看到函数的值仅取决于其输入参数。
This is only the beginning. As its name suggests, functional programming is centered around a theory of functions. 这仅仅是个开始。 顾名思义,函数式编程以函数理论为中心。
It would make sense to be able to pass them as arguments to other functions, and return a function from another function. Functions are considered <dfn>first class objects</dfn> in JavaScript, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments. 能够将它们作为参数传递给其他函数,从另一个函数返回一个函数是有意义的。 函数在 JavaScript 中被视为 <dfn>First Class Objects</dfn>,它们可以像任何其他对象一样使用。 它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。
Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at `Array.prototype.map()`, or more simply `map`. 让我们从一些简单的数组函数开始,这些函数是数组对象原型上的方法。 在本练习中,我们来了解下数组的 `map` 方法(即 `Array.prototype.map()`)。
The `map` method iterates over each item in an array and returns a new array containing the results of calling the callback function on each element. It does this without mutating the original array. 请记住,`map`方法是迭代数组中每一项的方式之一。 在对每个元素应用回调函数后,它会创建一个新数组(不改变原来的数组)。 它这样做时没有改变原始数组。
When the callback is used, it is passed three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `map` method was called. 当调用回调函数时,传入了三个参数。 第一个参数是当前正在处理的数组项。 第二个参数是当前数组项的索引值,第三个参数是在其上调用 `map` 方法的数组。
See below for an example using the `map` method on the `users` array to return a new array containing only the names of the users as elements. For simplicity, the example only uses the first argument of the callback. 看下在 `users` 上使用 `map` 方法的例子,返回了一个新数组只包含了用户的名字。 为了简化,例子里只使用了回调函数的第一个参数。
```js ```js
const users = [ const users = [
@ -30,16 +30,18 @@ const users = [
]; ];
const names = users.map(user => user.name); const names = users.map(user => user.name);
console.log(names); // [ 'John', 'Amy', 'camperCat' ] console.log(names);
``` ```
控制台将显示值 `[ 'John', 'Amy', 'camperCat' ]`
# --instructions-- # --instructions--
The `watchList` array holds objects with information on several movies. Use `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys to the `ratings` variable. The code in the editor currently uses a `for` loop to do this, so you should replace the loop functionality with your `map` expression. `watchList` 数组保存了包含一些电影信息的对象。 使用 `map` `watchList` 中提取标题(`title`)和评分(`rating`),并将新数组保存在 `ratings` 变量里。 目前编辑器中的代码是使用 `for` 循环实现,使用 `map` 表达式替换循环功能。
# --hints-- # --hints--
The `watchList` variable should not change. `watchList` 应保持不变。
```js ```js
assert( assert(
@ -47,19 +49,19 @@ assert(
); );
``` ```
Your code should not use a `for` loop. 不能使用 `for` 循环。
```js ```js
assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/)); assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
``` ```
Your code should use the `map` method. 你的代码应使用 `map` 方法。
```js ```js
assert(code.match(/\.map/g)); assert(code.match(/\.map/g));
``` ```
`ratings` should equal `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`. `ratings` 应等于 `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`
```js ```js
assert.deepEqual(ratings, [ assert.deepEqual(ratings, [

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7da9367417b2b2512b68 id: 587d7da9367417b2b2512b68
title: Use the reduce Method to Analyze Data title: 使用 reduce 方法分析数据
challengeType: 1 challengeType: 1
forumTopicId: 301313 forumTopicId: 301313
dashedName: use-the-reduce-method-to-analyze-data dashedName: use-the-reduce-method-to-analyze-data
@ -8,15 +8,15 @@ dashedName: use-the-reduce-method-to-analyze-data
# --description-- # --description--
`Array.prototype.reduce()`, or simply `reduce()`, is the most general of all array operations in JavaScript. You can solve almost any array processing problem using the `reduce` method. `reduce()`(即`Array.prototype.reduce()`),是 JavaScript 所有数组操作中最常用的方法。 几乎可以用`reduce`方法解决所有数组处理问题。
The `reduce` method allows for more general forms of array processing, and it's possible to show that both `filter` and `map` can be derived as special applications of `reduce`. The `reduce` method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration. `reduce`方法是处理数组更通用的方式,而且`filter``map`方法都可以当作是`reduce`的特殊实现。 `reduce`方法遍历数组中的每个项目并返回单个值(即字符串、数字、对象、数组)。 这是通过在每次迭代中调用一个回调函数来实现的。
The callback function accepts four arguments. The first argument is known as the accumulator, which gets assigned the return value of the callback function from the previous iteration, the second is the current element being processed, the third is the index of that element and the fourth is the array upon which `reduce` is called. 回调函数接受四个参数。 第一个参数称为叠加器,它是上一次迭代中回调函数的返回值,第二个参数是当前正在处理的数组元素,第三个参数是该参数的索引,第四个参数是在其上调用 `reduce` 方法的数组。
In addition to the callback function, `reduce` has an additional parameter which takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator. 除了回调函数,`reduce` 还有一个额外的参数做为叠加器的初始值。 如果没有第二个参数,会跳过第一次迭代,第二次迭代给叠加器传入数组的第一个元素。
See below for an example using `reduce` on the `users` array to return the sum of all the users' ages. For simplicity, the example only uses the first and second arguments. 见下面的例子,给 `users` 数组使用 `reduce` 方法,返回所有用户数组的和。 为了简化,例子仅使用了回调函数的第一个参数和第二个参数。
```js ```js
const users = [ const users = [
@ -26,10 +26,12 @@ const users = [
]; ];
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0); const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges); // 64 console.log(sumOfAges);
``` ```
In another example, see how an object can be returned containing the names of the users as properties with their ages as values. 这里控制台将显示值 `64`
在另一个例子里,查看如何返回一个包含用户名称做为属性,其年龄做为值的对象。
```js ```js
const users = [ const users = [
@ -42,16 +44,18 @@ const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age; obj[user.name] = user.age;
return obj; return obj;
}, {}); }, {});
console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 } console.log(usersObj);
``` ```
控制台将显示值 `{ John: 34, Amy: 20, camperCat: 10 }`
# --instructions-- # --instructions--
The variable `watchList` holds an array of objects with information on several movies. Use `reduce` to find the average IMDB rating of the movies **directed by Christopher Nolan**. Recall from prior challenges how to `filter` data and `map` over it to pull what you need. You may need to create other variables, and return the average rating from `getRating` function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations. `watchList` 是包含一些电影信息的对象。 使用 `reduce` 查找由 `Christopher Nolan` 导演的电影的 IMDB 评级平均值。 回想一下之前的挑战,如何 `filter` 数据,以及使用 `map` 来获取你想要的数据。 您可能需要创建其他变量,并从 `getRating` 函数返回平均评分。 请注意,评级在对象中是字符串,需要将其转换为数字再用于数学运算。
# --hints-- # --hints--
The `watchList` variable should not change. `watchList` 应保持不变。
```js ```js
assert( assert(
@ -59,25 +63,25 @@ assert(
); );
``` ```
Your code should use the `reduce` method. 应该使用`reduce`方法。
```js ```js
assert(code.match(/\.reduce/g)); assert(code.match(/\.reduce/g));
``` ```
The `getRating(watchList)` should equal 8.675. `getRating(watchList)` 应该等于 8.675
```js ```js
assert(getRating(watchList) === 8.675); assert(getRating(watchList) === 8.675);
``` ```
Your code should not use a `for` loop. 不能使用 `for` 循环。
```js ```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g)); assert(!code.match(/for\s*?\([\s\S]*?\)/g));
``` ```
Your code should return correct output after modifying the `watchList` object. 在修改 `watchList` 对象后应该返回正确的输出。
```js ```js
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55); assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7dab367417b2b2512b6f id: 587d7dab367417b2b2512b6f
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria title: 使用 some 方法检查数组中是否有元素是否符合条件
challengeType: 1 challengeType: 1
forumTopicId: 301314 forumTopicId: 301314
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
@ -8,43 +8,44 @@ dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-cr
# --description-- # --description--
The `some` method works with arrays to check if *any* element passes a particular test. It returns a Boolean value - `true` if any of the values meet the criteria, `false` if not. `some` 方法用于检测数组中*任何*元素是否满足指定条件。 如果有一个元素满足条件,返回布尔值 `true`,反之返回 `false`
For example, the following code would check if any element in the `numbers` array is less than 10: 举个例子,下面的代码检测数组`numbers`中是否有元素小于 10
```js ```js
var numbers = [10, 50, 8, 220, 110, 11]; var numbers = [10, 50, 8, 220, 110, 11];
numbers.some(function(currentValue) { numbers.some(function(currentValue) {
return currentValue < 10; return currentValue < 10;
}); });
// Returns true
``` ```
`some` 方法将返回 `true`
# --instructions-- # --instructions--
Use the `some` method inside the `checkPositive` function to check if any element in `arr` is positive. The function should return a Boolean value. `checkPositive` 函数值中使用 `some` 检查 `arr` 中是否有元素为正数。 函数应返回一个布尔值。
# --hints-- # --hints--
Your code should use the `some` method. 应该使用 `some` 方法。
```js ```js
assert(code.match(/\.some/g)); assert(code.match(/\.some/g));
``` ```
`checkPositive([1, 2, 3, -4, 5])` should return `true`. `checkPositive([1, 2, 3, -4, 5])` 应返回 `true`
```js ```js
assert(checkPositive([1, 2, 3, -4, 5])); assert(checkPositive([1, 2, 3, -4, 5]));
``` ```
`checkPositive([1, 2, 3, 4, 5])` should return `true`. `checkPositive([1, 2, 3, 4, 5])` 应返回 `true`
```js ```js
assert(checkPositive([1, 2, 3, 4, 5])); assert(checkPositive([1, 2, 3, 4, 5]));
``` ```
`checkPositive([-1, -2, -3, -4, -5])` should return `false`. `checkPositive([-1, -2, -3, -4, -5])` 应返回 `false`
```js ```js
assert(!checkPositive([-1, -2, -3, -4, -5])); assert(!checkPositive([-1, -2, -3, -4, -5]));

View File

@ -1,6 +1,6 @@
--- ---
id: a2f1d72d9b908d0bd72bb9f6 id: a2f1d72d9b908d0bd72bb9f6
title: 构建 Person 类 title: 创建一个人员对象
challengeType: 5 challengeType: 5
forumTopicId: 16020 forumTopicId: 16020
dashedName: make-a-person dashedName: make-a-person

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244df id: 56533eb9ac21ba0edf2244df
title: Multiple Identical Options in Switch Statements title: Múltiples opciones idénticas en las declaraciones "switch"
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cdBKWCV' videoUrl: 'https://scrimba.com/c/cdBKWCV'
forumTopicId: 18242 forumTopicId: 18242
@ -9,7 +9,7 @@ dashedName: multiple-identical-options-in-switch-statements
# --description-- # --description--
If the `break` statement is omitted from a `switch` statement's `case`, the following `case` statement(s) are executed until a `break` is encountered. If you have multiple inputs with the same output, you can represent them in a `switch` statement like this: Si la sentencia `break` es omitida en un caso (`case`) de una sentencia `switch`, las siguientes sentencias `case` serán ejecutadas hasta encontrar un `break`. Si tienes múltiples entradas con la misma salida, puedes representarlas en una sentencia `switch` como esta:
```js ```js
var result = ""; var result = "";
@ -24,81 +24,80 @@ switch(val) {
} }
``` ```
Cases for 1, 2, and 3 will all produce the same result. Los casos 1, 2 y 3 producirán el mismo resultado.
# --instructions-- # --instructions--
Write a switch statement to set `answer` for the following ranges: Escribe una declaración switch para establecer `answer` con los siguientes rangos:
`1-3` - "Low" `1-3` - `Low`
`4-6` - "Mid" `4-6` - `Mid`
`7-9` - "High" `7-9` - `High`
**Note** **Nota:** Necesitarás tener un `case` para cada número dentro del rango.
You will need to have a `case` statement for each number in the range.
# --hints-- # --hints--
`sequentialSizes(1)` should return "Low" `sequentialSizes(1)` debe devolver la cadena `Low`
```js ```js
assert(sequentialSizes(1) === 'Low'); assert(sequentialSizes(1) === 'Low');
``` ```
`sequentialSizes(2)` should return "Low" `sequentialSizes(2)` debe devolver la cadena `Low`
```js ```js
assert(sequentialSizes(2) === 'Low'); assert(sequentialSizes(2) === 'Low');
``` ```
`sequentialSizes(3)` should return "Low" `sequentialSizes(3)` debe devolver la cadena `Low`
```js ```js
assert(sequentialSizes(3) === 'Low'); assert(sequentialSizes(3) === 'Low');
``` ```
`sequentialSizes(4)` should return "Mid" `sequentialSizes(4)` debe devolver la cadena `Mid`
```js ```js
assert(sequentialSizes(4) === 'Mid'); assert(sequentialSizes(4) === 'Mid');
``` ```
`sequentialSizes(5)` should return "Mid" `sequentialSizes(5)` debe devolver la cadena `Mid`
```js ```js
assert(sequentialSizes(5) === 'Mid'); assert(sequentialSizes(5) === 'Mid');
``` ```
`sequentialSizes(6)` should return "Mid" `sequentialSizes(6)` debe devolver la cadena `Mid`
```js ```js
assert(sequentialSizes(6) === 'Mid'); assert(sequentialSizes(6) === 'Mid');
``` ```
`sequentialSizes(7)` should return "High" `sequentialSizes(7)` debe devolver la cadena `High`
```js ```js
assert(sequentialSizes(7) === 'High'); assert(sequentialSizes(7) === 'High');
``` ```
`sequentialSizes(8)` should return "High" `sequentialSizes(8)` debe devolver la cadena `High`
```js ```js
assert(sequentialSizes(8) === 'High'); assert(sequentialSizes(8) === 'High');
``` ```
`sequentialSizes(9)` should return "High" `sequentialSizes(9)` debe devolver la cadena `High`
```js ```js
assert(sequentialSizes(9) === 'High'); assert(sequentialSizes(9) === 'High');
``` ```
You should not use any `if` or `else` statements No debes utilizar las sentencias `if` o `else`
```js ```js
assert(!/else/g.test(code) || !/if/g.test(code)); assert(!/else/g.test(code) || !/if/g.test(code));
``` ```
You should have nine `case` statements Debes tener nueve sentencias `case`
```js ```js
assert(code.match(/case/g).length === 9); assert(code.match(/case/g).length === 9);

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244cf id: 56533eb9ac21ba0edf2244cf
title: Record Collection title: Colección de discos
challengeType: 1 challengeType: 1
forumTopicId: 18261 forumTopicId: 18261
dashedName: record-collection dashedName: record-collection
@ -8,21 +8,21 @@ dashedName: record-collection
# --description-- # --description--
You are given a JSON object representing a part of your musical album collection. Each album has a unique id number as its key and several other properties. Not all albums have complete information. Se te da un objeto JSON que representa una parte de tu colección de álbumes musicales. Cada álbum tiene un número de id único como clave y varias otras propiedades. No todos los álbumes tienen una información completa.
You start with an `updateRecords` function that takes an object like `collection`, an `id`, a `prop` (like `artist` or `tracks`), and a `value`. Complete the function using the rules below to modify the object passed to the function. Empiezas con una función `updateRecords` el cual toma un objeto `collection`, un `id`, una `prop` (como `artist` o `tracks`), y un `value`. Completa la funcn usando las reglas siguientes para modificar el objeto pasado a la funcn.
- Your function must always return the entire object. - Tu función siempre debe devolver el objeto completo.
- If `prop` isn't `tracks` and `value` isn't an empty string, update or set that album's `prop` to `value`. - Si `prop` no es `tracks` y `value` no es una cadena vacía, actualiza o establece la propiedad `prop` del album a `value`.
- If `prop` is `tracks` but the album doesn't have a `tracks` property, create an empty array and add `value` to it. - Si `prop` es `tracks` pero el álbum no tiene una propiedad `tracks`, crea un arreglo vacío y agrégale `value` a él.
- If `prop` is `tracks` and `value` isn't an empty string, add `value` to the end of the album's existing `tracks` array. - Si `prop` es `tracks` y `value` no es una cadena vacía, agrega `value` al final del arreglo de `tracks` existentes del álbum.
- If `value` is an empty string, delete the given `prop` property from the album. - Si `value` es una cadena vacía, elimina esa propiedad `prop` del álbum.
**Note:** A copy of the `collection` object is used for the tests. **Nota:** Una copia del objeto `collection` es usada para las pruebas.
# --hints-- # --hints--
After `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` should be `ABBA` Después de `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` debe ser la cadena `ABBA`
```js ```js
assert( assert(
@ -31,7 +31,7 @@ assert(
); );
``` ```
After `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have `Take a Chance on Me` as the last element. Después de `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")`, `tracks` debe tener la cadena `Take a Chance on Me` como último elemento.
```js ```js
assert( assert(
@ -41,14 +41,14 @@ assert(
); );
``` ```
After `updateRecords(collection, 2548, "artist", "")`, `artist` should not be set Después de `updateRecords(collection, 2548, "artist", "")`, `artist` no debe establecerse
```js ```js
updateRecords(_recordCollection, 2548, 'artist', ''); updateRecords(_recordCollection, 2548, 'artist', '');
assert(!_recordCollection[2548].hasOwnProperty('artist')); assert(!_recordCollection[2548].hasOwnProperty('artist'));
``` ```
After `updateRecords(collection, 1245, "tracks", "Addicted to Love")`, `tracks` should have `Addicted to Love` as the last element. Después de `updateRecords(collection, 1245, "tracks", "Addicted to Love")`, `tracks` debe tener la cadena `Addicted to Love` como último elemento.
```js ```js
assert( assert(
@ -58,7 +58,7 @@ assert(
); );
``` ```
After `updateRecords(collection, 2468, "tracks", "Free")`, `tracks` should have `1999` as the first element. Después de `updateRecords(collection, 2468, "tracks", "Free")`, `tracks` debe tener la cadena `1999` como primer elemento.
```js ```js
assert( assert(
@ -68,14 +68,14 @@ assert(
); );
``` ```
After `updateRecords(collection, 2548, "tracks", "")`, `tracks` should not be set Después de `updateRecords(collection, 2548, "tracks", "")`, `tracks` no debe establecerse
```js ```js
updateRecords(_recordCollection, 2548, 'tracks', ''); updateRecords(_recordCollection, 2548, 'tracks', '');
assert(!_recordCollection[2548].hasOwnProperty('tracks')); assert(!_recordCollection[2548].hasOwnProperty('tracks'));
``` ```
After `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be `Riptide` Después de `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` debe ser la cadena `Riptide`
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244e0 id: 56533eb9ac21ba0edf2244e0
title: Replacing If Else Chains with Switch title: Reemplazando cadenas de "If Else" por "Switch"
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/c3JE8fy' videoUrl: 'https://scrimba.com/c/c3JE8fy'
forumTopicId: 18266 forumTopicId: 18266
@ -9,7 +9,7 @@ dashedName: replacing-if-else-chains-with-switch
# --description-- # --description--
If you have many options to choose from, a `switch` statement can be easier to write than many chained `if`/`else if` statements. The following: Si tienes muchas opciones entre las que elegir, una sentencia `switch` puede ser más fácil de escribir que muchas sentencias `if`/`else if` encadenadas. Lo siguiente:
```js ```js
if (val === 1) { if (val === 1) {
@ -21,7 +21,7 @@ if (val === 1) {
} }
``` ```
can be replaced with: puede reemplazarse por:
```js ```js
switch(val) { switch(val) {
@ -38,65 +38,65 @@ switch(val) {
# --instructions-- # --instructions--
Change the chained `if`/`else if` statements into a `switch` statement. Cambia la cadena de sentencias `if`/`else if` por una sentencia `switch`.
# --hints-- # --hints--
You should not use any `else` statements anywhere in the editor No debes utilizar sentencias `else` en ningún lugar en el editor
```js ```js
assert(!/else/g.test(code)); assert(!/else/g.test(code));
``` ```
You should not use any `if` statements anywhere in the editor No debes utilizar sentencias `if` en ningún lugar en el editor
```js ```js
assert(!/if/g.test(code)); assert(!/if/g.test(code));
``` ```
You should have at least four `break` statements Debes tener al menos cuatro sentencias `break`
```js ```js
assert(code.match(/break/g).length >= 4); assert(code.match(/break/g).length >= 4);
``` ```
`chainToSwitch("bob")` should be "Marley" `chainToSwitch("bob")` debe ser la cadena `Marley`
```js ```js
assert(chainToSwitch('bob') === 'Marley'); assert(chainToSwitch('bob') === 'Marley');
``` ```
`chainToSwitch(42)` should be "The Answer" `chainToSwitch(42)` debe ser la cadena `The Answer`
```js ```js
assert(chainToSwitch(42) === 'The Answer'); assert(chainToSwitch(42) === 'The Answer');
``` ```
`chainToSwitch(1)` should be "There is no #1" `chainToSwitch(1)` debe ser la cadena `There is no #1`
```js ```js
assert(chainToSwitch(1) === 'There is no #1'); assert(chainToSwitch(1) === 'There is no #1');
``` ```
`chainToSwitch(99)` should be "Missed me by this much!" `chainToSwitch(99)` debe ser la cadena `Missed me by this much!`
```js ```js
assert(chainToSwitch(99) === 'Missed me by this much!'); assert(chainToSwitch(99) === 'Missed me by this much!');
``` ```
`chainToSwitch(7)` should be "Ate Nine" `chainToSwitch(7)` debe ser la cadena `Ate Nine`
```js ```js
assert(chainToSwitch(7) === 'Ate Nine'); assert(chainToSwitch(7) === 'Ate Nine');
``` ```
`chainToSwitch("John")` should be "" (empty string) `chainToSwitch("John")` debe ser `""` (cadena vacía)
```js ```js
assert(chainToSwitch('John') === ''); assert(chainToSwitch('John') === '');
``` ```
`chainToSwitch(156)` should be "" (empty string) `chainToSwitch(156)` debe ser `""` (cadena vacía)
```js ```js
assert(chainToSwitch(156) === ''); assert(chainToSwitch(156) === '');

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244dd id: 56533eb9ac21ba0edf2244dd
title: Selecting from Many Options with Switch Statements title: Seleccionando entre muchas opciones con declaración switch
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/c4mv4fm' videoUrl: 'https://scrimba.com/c/c4mv4fm'
forumTopicId: 18277 forumTopicId: 18277
@ -9,9 +9,9 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description-- # --description--
If you have many options to choose from, use a <dfn>switch</dfn> statement. A `switch` statement tests a value and can have many <dfn>case</dfn> statements which define various possible values. Statements are executed from the first matched `case` value until a `break` is encountered. Si tienes muchas opciones para elegir, usa una declaración <dfn>switch</dfn>. Una sentencia `switch` prueba un valor y puede tener muchas sentencias <dfn>case</dfn> que definen varios valores posibles. Las sentencias se ejecutan desde el primer valor `case` coincidente hasta que se encuentra un `break`.
Here is an example of a `switch` statement: Aquí hay un ejemplo de una declaración `switch`:
```js ```js
switch(lowercaseLetter) { switch(lowercaseLetter) {
@ -24,49 +24,49 @@ switch(lowercaseLetter) {
} }
``` ```
`case` values are tested with strict equality (`===`). The `break` tells JavaScript to stop executing statements. If the `break` is omitted, the next statement will be executed. Los valores en las sentencias `case` se prueban con igualdad estricta (`===`). El `break` le dice a JavaScript que deje de ejecutar declaraciones. Si se omite `break`, se ejecutara la siguiente sentencia.
# --instructions-- # --instructions--
Write a switch statement which tests `val` and sets `answer` for the following conditions: Escribe una declaración switch que pruebe `val` y establezca `answer` con las siguientes condiciones:
`1` - "alpha" `1` - `alpha`
`2` - "beta" `2` - `beta`
`3` - "gamma" `3` - `gamma`
`4` - "delta" `4` - `delta`
# --hints-- # --hints--
`caseInSwitch(1)` should have a value of "alpha" `caseInSwitch(1)` debe tener una cadena con valor `alpha`
```js ```js
assert(caseInSwitch(1) === 'alpha'); assert(caseInSwitch(1) === 'alpha');
``` ```
`caseInSwitch(2)` should have a value of "beta" `caseInSwitch(2)` debe tener una cadena con valor `beta`
```js ```js
assert(caseInSwitch(2) === 'beta'); assert(caseInSwitch(2) === 'beta');
``` ```
`caseInSwitch(3)` should have a value of "gamma" `caseInSwitch(3)` debe tener una cadena con valor `gamma`
```js ```js
assert(caseInSwitch(3) === 'gamma'); assert(caseInSwitch(3) === 'gamma');
``` ```
`caseInSwitch(4)` should have a value of "delta" `caseInSwitch(4)` debe tener una cadena con valor `delta`
```js ```js
assert(caseInSwitch(4) === 'delta'); assert(caseInSwitch(4) === 'delta');
``` ```
You should not use any `if` or `else` statements No debes usar ninguna sentencia `if` o `else`
```js ```js
assert(!/else/g.test(code) || !/if/g.test(code)); assert(!/else/g.test(code) || !/if/g.test(code));
``` ```
You should have at least 3 `break` statements Debes tener al menos 3 declaraciones `break`
```js ```js
assert(code.match(/break/g).length > 2); assert(code.match(/break/g).length > 2);

View File

@ -13,15 +13,12 @@ Con las variables de arreglos (`array`) de JavaScript, podemos almacenar varios
Inicias una declaración de arreglo con un corchete de apertura, lo terminas con un corchete de cierre, y pones una coma entre cada entrada, de esta forma: Inicias una declaración de arreglo con un corchete de apertura, lo terminas con un corchete de cierre, y pones una coma entre cada entrada, de esta forma:
`var sandwich = ["peanut butter", "jelly", "bread"]`. `var sandwich = ["peanut butter", "jelly", "bread"]`
# --instructions-- # --instructions--
Modifica el nuevo arreglo `myArray` para que contenga tanto una `string` como un `number` (en ese orden). Modifica el nuevo arreglo `myArray` para que contenga tanto una `string` como un `number` (en ese orden).
**Sugerencia**
Consulta el código de ejemplo en el editor de texto si te quedas atascado.
# --hints-- # --hints--
`myArray` debe ser un arreglo (`array`). `myArray` debe ser un arreglo (`array`).

View File

@ -1,6 +1,6 @@
--- ---
id: cf1111c1c11feddfaeb4bdef id: cf1111c1c11feddfaeb4bdef
title: Subtract One Number from Another with JavaScript title: Resta un número de otro con JavaScript
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cP3yQtk' videoUrl: 'https://scrimba.com/c/cP3yQtk'
forumTopicId: 18314 forumTopicId: 18314
@ -9,29 +9,30 @@ dashedName: subtract-one-number-from-another-with-javascript
# --description-- # --description--
We can also subtract one number from another. También podemos restar un número de otro.
JavaScript uses the `-` symbol for subtraction. JavaScript utiliza el símbolo `-` para restar.
**Example** **Ejemplo**
```js ```js
myVar = 12 - 6; // assigned 6 myVar = 12 - 6;
``` ```
`myVar` tendrá el valor `6`.
# --instructions-- # --instructions--
Change the `0` so the difference is `12`. Cambia el `0` para que la diferencia sea `12`.
# --hints-- # --hints--
The variable `difference` should be equal to 12. La variable `difference` debe ser igual a 12.
```js ```js
assert(difference === 12); assert(difference === 12);
``` ```
You should only subtract one number from 45. Sólo debes restar un número de 45.
```js ```js
assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code))); assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code)));

View File

@ -1,6 +1,6 @@
--- ---
id: 567af2437cbaa8c51670a16c id: 567af2437cbaa8c51670a16c
title: Testing Objects for Properties title: Verifica las propiedades de un objeto
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/c6Wz4ySr' videoUrl: 'https://scrimba.com/c/c6Wz4ySr'
forumTopicId: 18324 forumTopicId: 18324
@ -9,26 +9,28 @@ dashedName: testing-objects-for-properties
# --description-- # --description--
Sometimes it is useful to check if the property of a given object exists or not. We can use the `.hasOwnProperty(propname)` method of objects to determine if that object has the given property name. `.hasOwnProperty()` returns `true` or `false` if the property is found or not. A veces es útil comprobar si existe o no la propiedad de un objeto dado. Podemos utilizar el método `.hasOwnProperty(propname)` para determinar si un objeto tiene una propiedad con ese nombre. `.hasOwnProperty()` devuelve `true` o `false` si se encuentra la propiedad o no.
**Example** **Por ejemplo**
```js ```js
var myObj = { var myObj = {
top: "hat", top: "hat",
bottom: "pants" bottom: "pants"
}; };
myObj.hasOwnProperty("top"); // true myObj.hasOwnProperty("top");
myObj.hasOwnProperty("middle"); // false myObj.hasOwnProperty("middle");
``` ```
El primer `hasOwnProperty` devuelve `true`, mientras que el segundo devuelve `false`.
# --instructions-- # --instructions--
Modify the function `checkObj` to test if an object passed to the function (`obj`) contains a specific property (`checkProp`). If the property is found, return that property's value. If not, return `"Not Found"`. Modifica la funcn `checkObj` para verificar si el objeto `obj` pasado a la función contiene la propiedad `checkProp`. Si la propiedad es encontrada, devuelve el valor de la propiedad. Si no, devuelve `"Not Found"`.
# --hints-- # --hints--
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return `"pony"`. `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` debe devolver la cadena`pony`.
```js ```js
assert( assert(
@ -36,7 +38,7 @@ assert(
); );
``` ```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return `"kitten"`. `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` debe devolver la cadena `kitten`.
```js ```js
assert( assert(
@ -44,7 +46,7 @@ assert(
); );
``` ```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return `"Not Found"`. `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` debe devolver la cadena `Not Found`.
```js ```js
assert( assert(
@ -53,19 +55,19 @@ assert(
); );
``` ```
`checkObj({city: "Seattle"}, "city")` should return `"Seattle"`. `checkObj({city: "Seattle"}, "city")` debe devolver la cadena `Seattle`.
```js ```js
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle'); assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
``` ```
`checkObj({city: "Seattle"}, "district")` should return `"Not Found"`. `checkObj({city: "Seattle"}, "district")` debe devolver la cadena `Not Found`.
```js ```js
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found'); assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
``` ```
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return `"Not Found"`. `checkObj({pet: "kitten", bed: "sleigh"}, "gift")` debe devolver la cadena `Not Found`.
```js ```js
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found'); assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244ba id: 56533eb9ac21ba0edf2244ba
title: Understand String Immutability title: Comprende la inmutabilidad de las cadenas
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cWPVaUR' videoUrl: 'https://scrimba.com/c/cWPVaUR'
forumTopicId: 18331 forumTopicId: 18331
@ -9,16 +9,16 @@ dashedName: understand-string-immutability
# --description-- # --description--
In JavaScript, `String` values are <dfn>immutable</dfn>, which means that they cannot be altered once created. En JavaScript, los valores de cadena (`String`) son <dfn>inmutables</dfn>, lo que significa que no pueden ser alterados una vez creados.
For example, the following code: Por ejemplo, el siguiente código:
```js ```js
var myStr = "Bob"; var myStr = "Bob";
myStr[0] = "J"; myStr[0] = "J";
``` ```
cannot change the value of `myStr` to "Job", because the contents of `myStr` cannot be altered. Note that this does *not* mean that `myStr` cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change `myStr` would be to assign it with a new string, like this: no puede cambiar el valor de `myStr` a `Job`, porque el contenido de `myStr` no puede ser alterado. Ten en cuenta que esto *no* significa que `myStr` no puede cambiarse, solo que los caracteres individuales de una <dfn>cadena literal</dfn> no pueden ser cambiados. La única forma de cambiar `myStr` sería asignarla con una nueva cadena, como esta:
```js ```js
var myStr = "Bob"; var myStr = "Bob";
@ -27,17 +27,17 @@ myStr = "Job";
# --instructions-- # --instructions--
Correct the assignment to `myStr` so it contains the string value of `Hello World` using the approach shown in the example above. Corrige la asignación de `myStr` para que contenga el valor de cadena `Hello World` usando el método mostrado en el ejemplo anterior.
# --hints-- # --hints--
`myStr` should have a value of `Hello World`. `myStr` debe tener una cadena con valor `Hello World`.
```js ```js
assert(myStr === 'Hello World'); assert(myStr === 'Hello World');
``` ```
You should not change the code above the specified comment. No debes cambiar el código por encima del comentario especificado.
```js ```js
assert(/myStr = "Jello World"/.test(code)); assert(/myStr = "Jello World"/.test(code));

View File

@ -1,6 +1,6 @@
--- ---
id: bd7123c9c441eddfaeb5bdef id: bd7123c9c441eddfaeb5bdef
title: Understanding Boolean Values title: Comprende los valores booleanos
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/c9Me8t4' videoUrl: 'https://scrimba.com/c/c9Me8t4'
forumTopicId: 301176 forumTopicId: 301176
@ -9,24 +9,23 @@ dashedName: understanding-boolean-values
# --description-- # --description--
Another data type is the <dfn>Boolean</dfn>. `Booleans` may only be one of two values: `true` or `false`. They are basically little on-off switches, where `true` is "on" and `false` is "off." These two states are mutually exclusive. Otro tipo de datos es el <dfn>Booleano</dfn>. Los booleanos solo pueden ser uno de dos valores: `true` (verdadero) o `false` (falso). Básicamente son pequeños interruptores de encendido, donde `true` es encendido y `false` es apagado. Estos dos estados se excluyen mutuamente.
**Note** **Nota** Los valores del tipo booleano nunca se escriben con comillas. Las cadenas `"true"` y `"false"` no son booleanos y no tienen ningún significado especial en JavaScript.
`Boolean` values are never written with quotes. The `strings` `"true"` and `"false"` are not `Boolean` and have no special meaning in JavaScript.
# --instructions-- # --instructions--
Modify the `welcomeToBooleans` function so that it returns `true` instead of `false` when the run button is clicked. Modifica la función `welcomeToBooleans` para que devuelva `true` en lugar de `false` cuando se haga clic en el botón de ejecución.
# --hints-- # --hints--
The `welcomeToBooleans()` function should return a boolean (true/false) value. La función `welcomeToBooleans()` debe devolver un valor booleano (`true` o `false`).
```js ```js
assert(typeof welcomeToBooleans() === 'boolean'); assert(typeof welcomeToBooleans() === 'boolean');
``` ```
`welcomeToBooleans()` should return true. `welcomeToBooleans()` debe devolver `true`.
```js ```js
assert(welcomeToBooleans() === true); assert(welcomeToBooleans() === true);

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244ab id: 56533eb9ac21ba0edf2244ab
title: Comprender la sensibilidad de mayúsculas en las variables title: Comprendiendo la sensibilidad de mayúsculas en las variables
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cd6GDcD' videoUrl: 'https://scrimba.com/c/cd6GDcD'
forumTopicId: 18334 forumTopicId: 18334
@ -27,8 +27,9 @@ var thisVariableNameIsSoLong;
# --instructions-- # --instructions--
Modifica las declaraciones y asignaciones existentes para que sus nombres usen <dfn>camelCase</dfn>. Modifica las declaraciones y asignaciones existentes para que sus nombres usen <dfn>camelCase</dfn>.
No crees nuevas variables.
No crees ninguna variable nueva.
# --hints-- # --hints--
@ -38,7 +39,7 @@ No crees nuevas variables.
assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10); assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
``` ```
`properCamelCase` debe definirse y tener un valor de `"A String"`. `properCamelCase` debe definirse y tener una cadena con valor `A String`.
```js ```js
assert( assert(
@ -46,7 +47,7 @@ assert(
); );
``` ```
`titleCaseOver` debe definirse y tener un valor de `9000`. `titleCaseOver` debe definirse y tener una cadena con valor `9000`.
```js ```js
assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000); assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000);

View File

@ -1,6 +1,6 @@
--- ---
id: 598e8944f009e646fc236146 id: 598e8944f009e646fc236146
title: Understanding Undefined Value returned from a Function title: Comprendiendo el valor indefinido devuelto por una funcn
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/ce2p7cL' videoUrl: 'https://scrimba.com/c/ce2p7cL'
forumTopicId: 301177 forumTopicId: 301177
@ -9,45 +9,45 @@ dashedName: understanding-undefined-value-returned-from-a-function
# --description-- # --description--
A function can include the `return` statement but it does not have to. In the case that the function doesn't have a `return` statement, when you call it, the function processes the inner code but the returned value is `undefined`. Una función puede incluir la declaración de devolución (`return`) pero no tiene por qué hacerlo. En el caso de que la función no tenga una declaración de devolución (`return`), cuando la llames, la funcn procesa el código interno, pero el valor devuelto es `undefined` (indefinido).
**Example** **Ejemplo**
```js ```js
var sum = 0; var sum = 0;
function addSum(num) { function addSum(num) {
sum = sum + num; sum = sum + num;
} }
addSum(3); // sum will be modified but returned value is undefined addSum(3);
``` ```
`addSum` is a function without a `return` statement. The function will change the global `sum` variable but the returned value of the function is `undefined`. `addSum` es una función sin una declaración de devolución (`return`). La función cambiará la variable global `sum` pero el valor devuelto de la funcn es `undefined`.
# --instructions-- # --instructions--
Create a function `addFive` without any arguments. This function adds 5 to the `sum` variable, but its returned value is `undefined`. Crea una funcn `addFive` sin ningún argumento. Esta función suma 5 a la variable `sum`, pero su valor devuelto es `undefined`.
# --hints-- # --hints--
`addFive` should be a function. `addFive` debe ser una funcn.
```js ```js
assert(typeof addFive === 'function'); assert(typeof addFive === 'function');
``` ```
Once both functions have ran, the `sum` should be equal to 8. Una vez que ambas funciones hayan sido ejecutadas, la suma (`sum`) debe ser igual a `8`.
```js ```js
assert(sum === 8); assert(sum === 8);
``` ```
Returned value from `addFive` should be `undefined`. El valor devuelto por `addFive` debe ser `undefined`.
```js ```js
assert(addFive() === undefined); assert(addFive() === undefined);
``` ```
Inside the `addFive` function, you should add `5` to the `sum` variable. Dentro de la función `addFive`, debes sumar `5` a la variable `sum`.
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244aa id: 56533eb9ac21ba0edf2244aa
title: Understanding Uninitialized Variables title: Comprendiendo las variables no inicializadas
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cBa2JAL' videoUrl: 'https://scrimba.com/c/cBa2JAL'
forumTopicId: 18335 forumTopicId: 18335
@ -9,33 +9,33 @@ dashedName: understanding-uninitialized-variables
# --description-- # --description--
When JavaScript variables are declared, they have an initial value of `undefined`. If you do a mathematical operation on an `undefined` variable your result will be `NaN` which means <dfn>"Not a Number"</dfn>. If you concatenate a string with an `undefined` variable, you will get a literal <dfn>string</dfn> of `"undefined"`. Cuando las variables de JavaScript son declaradas, tienen un valor inicial de `undefined` (indefinido). Si haces una operación matemática en una variable `undefined`, tu resultado será `NaN` lo que significa <dfn>"Not a Number"</dfn> (no es un número). Si concatenas una cadena con una variable `undefined`, obtendrás una <dfn>cadena</dfn> literal con valor `undefined`.
# --instructions-- # --instructions--
Initialize the three variables `a`, `b`, and `c` with `5`, `10`, and `"I am a"` respectively so that they will not be `undefined`. Inicializa las tres variables `a`, `b`, y `c` con `5`, `10` y `"I am a"` respectivamente para que no sean `undefined`.
# --hints-- # --hints--
`a` should be defined and evaluated to have the value of `6`. `a` debe ser definido y evaluado para tener el valor de `6`.
```js ```js
assert(typeof a === 'number' && a === 6); assert(typeof a === 'number' && a === 6);
``` ```
`b` should be defined and evaluated to have the value of `15`. `b` debe ser definido y evaluado para tener el valor de `15`.
```js ```js
assert(typeof b === 'number' && b === 15); assert(typeof b === 'number' && b === 15);
``` ```
`c` should not contain `undefined` and should have a value of "I am a String!" `c` no debe contener `undefined` y debe tener una cadena con valor `I am a String!`
```js ```js
assert(!/undefined/.test(c) && c === 'I am a String!'); assert(!/undefined/.test(c) && c === 'I am a String!');
``` ```
You should not change code below the specified comment. No debes cambiar el código debajo del comentario especificado.
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 56bbb991ad1ed5201cd392d1 id: 56bbb991ad1ed5201cd392d1
title: Updating Object Properties title: Actualizando las propiedades de un objeto
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yEJT4' videoUrl: 'https://scrimba.com/c/c9yEJT4'
forumTopicId: 18336 forumTopicId: 18336
@ -9,9 +9,9 @@ dashedName: updating-object-properties
# --description-- # --description--
After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update. Después de haber creado un objeto de JavaScript, puedes actualizar sus propiedades en cualquier momento tal y como actualizarías cualquier otra variable. Puedes utilizar tanto la notación de puntos como la notación de corchetes para actualizar.
For example, let's look at `ourDog`: Por ejemplo, veamos `ourDog`:
```js ```js
var ourDog = { var ourDog = {
@ -22,21 +22,21 @@ var ourDog = {
}; };
``` ```
Since he's a particularly happy dog, let's change his name to "Happy Camper". Here's how we update his object's name property: `ourDog.name = "Happy Camper";` or `ourDog["name"] = "Happy Camper";` Now when we evaluate `ourDog.name`, instead of getting "Camper", we'll get his new name, "Happy Camper". Puesto que es un perro particularmente feliz, vamos a cambiar su nombre por la cadena `Happy Camper`. Así es como actualizamos la propiedad del nombre del objeto: `ourDog.name = "Happy Camper";` o `ourDog["name"] = "Happy Camper";`. Ahora cuando evaluamos `ourDog.name`, en lugar de obtener `Camper`, vamos a obtener su nuevo nombre, `Happy Camper`.
# --instructions-- # --instructions--
Update the `myDog` object's name property. Let's change her name from "Coder" to "Happy Coder". You can use either dot or bracket notation. Actualiza la propiedad nombre del objeto `myDog`. Cambiemos su nombre de `Coder` a `Happy Coder`. Puedes utilizar tanto la notación de puntos como la notación de corchetes.
# --hints-- # --hints--
You should update `myDog`'s `"name"` property to equal "Happy Coder". Debes actualizar la propiedad `name` de `myDog` para que sea igual a la cadena `Happy Coder`.
```js ```js
assert(/happy coder/gi.test(myDog.name)); assert(/happy coder/gi.test(myDog.name));
``` ```
You should not edit the `myDog` definition. No debes editar la definición de `myDog`.
```js ```js
assert(/"name": "Coder"/.test(code)); assert(/"name": "Coder"/.test(code));

View File

@ -1,6 +1,6 @@
--- ---
id: bd7123c9c549eddfaeb5bdef id: bd7123c9c549eddfaeb5bdef
title: Use Bracket Notation to Find the First Character in a String title: Utiliza la notación de corchetes para encontrar el primer carácter en una cadena
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8JwhW' videoUrl: 'https://scrimba.com/c/ca8JwhW'
forumTopicId: 18341 forumTopicId: 18341
@ -9,34 +9,36 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
# --description-- # --description--
<dfn>Bracket notation</dfn> is a way to get a character at a specific `index` within a string. La <dfn>notación de corchetes</dfn> es una forma de obtener un carácter en un índice (index) específico dentro de una cadena.
Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing. La mayoría de lenguajes de programación modernos, como JavaScript, no empiezan a contar desde 1 como lo hacen los humanos. Empiezan desde 0. Esto se conoce como indexación <dfn>basada en cero</dfn>.
For example, the character at index 0 in the word "Charles" is "C". So if `var firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`. Por ejemplo, el carácter en el índice 0 de la palabra `Charles` es `C`. Así que si declaramos `var firstName = "Charles"`, puedes obtener el valor de la primera letra de la cadena usando `firstName[0]`.
Example: Ejemplo:
```js ```js
var firstName = "Charles"; var firstName = "Charles";
var firstLetter = firstName[0]; // firstLetter is "C" var firstLetter = firstName[0];
``` ```
`firstLetter` tendrá una cadena con valor `C`.
# --instructions-- # --instructions--
Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`. Utiliza notación de corchetes para encontrar el primer carácter en la variable `lastName` y asígnalo a `firstLetterOfLastName`.
**Hint:** Try looking at the example above if you get stuck. **Sugerencia:** Intenta mirar el ejemplo de arriba si te quedas atascado.
# --hints-- # --hints--
The `firstLetterOfLastName` variable should have the value of `L`. La variable `firstLetterOfLastName` debe tener el valor de `L`.
```js ```js
assert(firstLetterOfLastName === 'L'); assert(firstLetterOfLastName === 'L');
``` ```
You should use bracket notation. Debes usar la notación de corchetes.
```js ```js
assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/)); assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));

View File

@ -1,6 +1,6 @@
--- ---
id: bd7123c9c451eddfaeb5bdef id: bd7123c9c451eddfaeb5bdef
title: Utilice la notación de corchete para encontrar el último carácter en una cadena title: Utiliza la notación de corchetes para encontrar el último carácter en una cadena
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cBZQGcv' videoUrl: 'https://scrimba.com/c/cBZQGcv'
forumTopicId: 18342 forumTopicId: 18342
@ -9,7 +9,7 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
# --description-- # --description--
Con el fin de obtener la última letra de una cadena, puede restar uno a la longitud del texto. Con el fin de obtener la última letra de una cadena, puedes restar uno a la longitud del texto.
Por ejemplo, si `var firstName = "Charles"`, puedes obtener el valor de la última letra de la cadena usando `firstName[firstName.length - 1]`. Por ejemplo, si `var firstName = "Charles"`, puedes obtener el valor de la última letra de la cadena usando `firstName[firstName.length - 1]`.
@ -17,9 +17,11 @@ Ejemplo:
```js ```js
var firstName = "Charles"; var firstName = "Charles";
var lastLetter = firstName[firstName.length - 1]; // lastLetter is "s" var lastLetter = firstName[firstName.length - 1];
``` ```
`lastLetter` tendrá una cadena con valor `s`.
# --instructions-- # --instructions--
Usa <dfn>notación de corchetes</dfn> para encontrar el último carácter en la variable `lastName`. Usa <dfn>notación de corchetes</dfn> para encontrar el último carácter en la variable `lastName`.
@ -28,7 +30,7 @@ Usa <dfn>notación de corchetes</dfn> para encontrar el último carácter en la
# --hints-- # --hints--
`lastLetterOfLastName` debe ser "e". `lastLetterOfLastName` debe ser la letra `e`.
```js ```js
assert(lastLetterOfLastName === 'e'); assert(lastLetterOfLastName === 'e');

View File

@ -1,6 +1,6 @@
--- ---
id: bd7123c9c450eddfaeb5bdef id: bd7123c9c450eddfaeb5bdef
title: Use Bracket Notation to Find the Nth Character in a String title: Utiliza la notación de corchetes para encontrar el enésimo carácter en una cadena
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cWPVJua' videoUrl: 'https://scrimba.com/c/cWPVJua'
forumTopicId: 18343 forumTopicId: 18343
@ -9,32 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string
# --description-- # --description--
You can also use <dfn>bracket notation</dfn> to get the character at other positions within a string. También puedes usar <dfn>notación de corchetes</dfn> para obtener el carácter en otras posiciones dentro de una cadena.
Remember that computers start counting at `0`, so the first character is actually the zeroth character. Recuerda que las computadoras empiezan a contar desde `0`, así que el primer carácter es en realidad el carácter cero.
Example: Ejemplo:
```js ```js
var firstName = "Ada"; var firstName = "Ada";
var secondLetterOfFirstName = firstName[1]; // secondLetterOfFirstName is "d" var secondLetterOfFirstName = firstName[1];
``` ```
`secondLetterOfFirstName` tendrá una cadena con valor `d`.
# --instructions-- # --instructions--
Let's try to set `thirdLetterOfLastName` to equal the third letter of the `lastName` variable using bracket notation. Intentemos establecer `thirdLetterOfLastName` (tercera letra del apellido) para que sea igual a la tercera letra de la variable `lastName` usando notación de corchetes.
**Hint:** Try looking at the example above if you get stuck. **Sugerencia:** Intenta mirar el ejemplo de arriba si te quedas atascado.
# --hints-- # --hints--
The `thirdLetterOfLastName` variable should have the value of `v`. La variable `thirdLetterOfLastName` debe tener el valor de `v`.
```js ```js
assert(thirdLetterOfLastName === 'v'); assert(thirdLetterOfLastName === 'v');
``` ```
You should use bracket notation. Debes usar la notación de corchetes.
```js ```js
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/)); assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));

View File

@ -1,6 +1,6 @@
--- ---
id: bd7123c9c452eddfaeb5bdef id: bd7123c9c452eddfaeb5bdef
title: Use Bracket Notation to Find the Nth-to-Last Character in a String title: Utiliza la notación de corchetes para encontrar el carácter enésimo final en una cadena
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cw4vkh9' videoUrl: 'https://scrimba.com/c/cw4vkh9'
forumTopicId: 18344 forumTopicId: 18344
@ -9,32 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
# --description-- # --description--
You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character. Puedes usar el mismo principio que acabamos de usar para recuperar el último carácter de una cadena para recuperar el carácter enésimo final.
For example, you can get the value of the third-to-last letter of the `var firstName = "Charles"` string by using `firstName[firstName.length - 3]` Por ejemplo, puedes obtener el valor de la antepenúltima letra de la cadena `var firstName = "Charles"` usando `firstName[firstName.length - 3]`
Example: Ejemplo:
```js ```js
var firstName = "Charles"; var firstName = "Charles";
var thirdToLastLetter = firstName[firstName.length - 3]; // thirdToLastLetter is "l" var thirdToLastLetter = firstName[firstName.length - 3];
``` ```
`thirdToLastLetter` tendrá una cadena con valor `l`.
# --instructions-- # --instructions--
Use <dfn>bracket notation</dfn> to find the second-to-last character in the `lastName` string. Usa <dfn>notación de corchetes</dfn> para encontrar el penúltimo carácter en la cadena `lastName`.
**Hint:** Try looking at the example above if you get stuck. **Sugerencia:** Intenta mirar el ejemplo de arriba si te quedas atascado.
# --hints-- # --hints--
`secondToLastLetterOfLastName` should be "c". `secondToLastLetterOfLastName` debe ser la letra `c`.
```js ```js
assert(secondToLastLetterOfLastName === 'c'); assert(secondToLastLetterOfLastName === 'c');
``` ```
You should use `.length` to get the second last letter. Debes usar `.length` para obtener la penúltima letra.
```js ```js
assert(code.match(/\.length/g).length > 0); assert(code.match(/\.length/g).length > 0);

View File

@ -1,6 +1,6 @@
--- ---
id: cf1111c1c12feddfaeb3bdef id: cf1111c1c12feddfaeb3bdef
title: Use Conditional Logic with If Statements title: Usa lógica condicional con las sentencias "If"
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cy87mf3' videoUrl: 'https://scrimba.com/c/cy87mf3'
forumTopicId: 18348 forumTopicId: 18348
@ -9,15 +9,15 @@ dashedName: use-conditional-logic-with-if-statements
# --description-- # --description--
`If` statements are used to make decisions in code. The keyword `if` tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as `Boolean` conditions and they may only be `true` or `false`. Las sentencias `If` son utilizadas para tomar decisiones en el código. La palabra clave `if` le dice a JavaScript que ejecute el código entre llaves bajo ciertas condiciones, definidas en los paréntesis. Estas condiciones son conocidas como condiciones booleanas (`Boolean`) y sólo pueden ser `true` o `false`.
When the condition evaluates to `true`, the program executes the statement inside the curly braces. When the Boolean condition evaluates to `false`, the statement inside the curly braces will not execute. Cuando la condición se evalúa como `true`, el programa ejecuta el comando dentro de las llaves. Cuando la condición booleana se evalúa como `false`, la sentencia dentro de las llaves no se ejecutará.
**Pseudocode** **Pseudocódigo**
<blockquote>if (<i>condition is true</i>) {<br>  <i>statement is executed</i><br>}</blockquote> <blockquote>si (<i>la condición es verdadera</i>) {<br>  <i>la sentencia es ejecutada</i><br>}</blockquote>
**Example** **Ejemplo**
```js ```js
function test (myCondition) { function test (myCondition) {
@ -26,43 +26,45 @@ function test (myCondition) {
} }
return "It was false"; return "It was false";
} }
test(true); // returns "It was true" test(true);
test(false); // returns "It was false" test(false);
``` ```
When `test` is called with a value of `true`, the `if` statement evaluates `myCondition` to see if it is `true` or not. Since it is `true`, the function returns `"It was true"`. When we call `test` with a value of `false`, `myCondition` is *not* `true` and the statement in the curly braces is not executed and the function returns `"It was false"`. `test(true)` devuelve la cadena `It was true` y `test(false)` devuelve la cadena `It was false`.
Cuando `test` es llamada con un valor de `true`, la sentencia `if` evalúa `myCondition` (mi condición) para ver si es `true` o no. Puesto que es `true`, la función devuelve `It was true`. Cuando llamamos a `test` con un valor de `false`, `myCondition` *no* es `true`, la sentencia dentro de las llaves no se ejecuta y la función devuelve `It was false`.
# --instructions-- # --instructions--
Create an `if` statement inside the function to return `"Yes, that was true"` if the parameter `wasThatTrue` is `true` and return `"No, that was false"` otherwise. Crea una sentencia `if` dentro de la función que devuelva `Yes, that was true` si el parámetro `wasThatTrue` es `true` y devuelva `No, that was false` en caso contrario.
# --hints-- # --hints--
`trueOrFalse` should be a function `trueOrFalse` debe ser una funcn
```js ```js
assert(typeof trueOrFalse === 'function'); assert(typeof trueOrFalse === 'function');
``` ```
`trueOrFalse(true)` should return a string `trueOrFalse(true)` debe devolver una cadena
```js ```js
assert(typeof trueOrFalse(true) === 'string'); assert(typeof trueOrFalse(true) === 'string');
``` ```
`trueOrFalse(false)` should return a string `trueOrFalse(false)` debe devolver una cadena
```js ```js
assert(typeof trueOrFalse(false) === 'string'); assert(typeof trueOrFalse(false) === 'string');
``` ```
`trueOrFalse(true)` should return "Yes, that was true" `trueOrFalse(true)` debe devolver la cadena `Yes, that was true`
```js ```js
assert(trueOrFalse(true) === 'Yes, that was true'); assert(trueOrFalse(true) === 'Yes, that was true');
``` ```
`trueOrFalse(false)` should return "No, that was false" `trueOrFalse(false)` debe devolver la cadena `No, that was false`
```js ```js
assert(trueOrFalse(false) === 'No, that was false'); assert(trueOrFalse(false) === 'No, that was false');

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b7e367417b2b2512b21 id: 587d7b7e367417b2b2512b21
title: Use Multiple Conditional (Ternary) Operators title: Usa múltiples operadores condicionales (ternarios)
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cyWJBT4' videoUrl: 'https://scrimba.com/c/cyWJBT4'
forumTopicId: 301179 forumTopicId: 301179
@ -9,9 +9,9 @@ dashedName: use-multiple-conditional-ternary-operators
# --description-- # --description--
In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions. En el desafío anterior, usaste un único operador condicional. También puedes encadenarlos para comprobar múltiples condiciones.
The following function uses if, else if, and else statements to check multiple conditions: La siguiente función utiliza sentencias `if`, `else if`, y `else` para comprobar múltiples condiciones:
```js ```js
function findGreaterOrEqual(a, b) { function findGreaterOrEqual(a, b) {
@ -27,7 +27,7 @@ function findGreaterOrEqual(a, b) {
} }
``` ```
The above function can be re-written using multiple conditional operators: La funcn anterior puede ser reescrita utilizando múltiples operadores condicionales:
```js ```js
function findGreaterOrEqual(a, b) { function findGreaterOrEqual(a, b) {
@ -37,7 +37,7 @@ function findGreaterOrEqual(a, b) {
} }
``` ```
It is considered best practice to format multiple conditional operators such that each condition is on a separate line, as shown above. Using multiple conditional operators without proper indentation may make your code hard to read. For example: Se considera buena práctica dar formato a múltiples operadores condicionales de forma que cada condición esté en una línea separada, como se muestra arriba. Usar múltiples operadores condicionales sin una indentación adecuada puede hacer tu código difícil de leer. Por ejemplo:
```js ```js
function findGreaterOrEqual(a, b) { function findGreaterOrEqual(a, b) {
@ -47,29 +47,29 @@ function findGreaterOrEqual(a, b) {
# --instructions-- # --instructions--
In the `checkSign` function, use multiple conditional operators - following the recommended format used in `findGreaterOrEqual` - to check if a number is positive, negative or zero. The function should return `"positive"`, `"negative"` or `"zero"`. En la función `checkSign`, usa múltiples operadores condicionales (siguiendo el formato recomendado usado en `findGreaterOrEqual`) para comprobar si un número es positivo, negativo o cero. La función debe devolver `positive`, `negative` o `zero`.
# --hints-- # --hints--
`checkSign` should use multiple conditional operators `checkSign` debe utilizar múltiples operadores condicionales
```js ```js
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code)); assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code));
``` ```
`checkSign(10)` should return "positive". Note that capitalization matters `checkSign(10)` debe devolver la cadena `positive`. Ten en cuenta que la capitalización importa
```js ```js
assert(checkSign(10) === 'positive'); assert(checkSign(10) === 'positive');
``` ```
`checkSign(-12)` should return "negative". Note that capitalization matters `checkSign(-12)` debe devolver la cadena `negative`. Ten en cuenta que la capitalización importa
```js ```js
assert(checkSign(-12) === 'negative'); assert(checkSign(-12) === 'negative');
``` ```
`checkSign(0)` should return "zero". Note that capitalization matters `checkSign(0)` debe devolver la cadena `zero`. Ten en cuenta que la capitalización importa
```js ```js
assert(checkSign(0) === 'zero'); assert(checkSign(0) === 'zero');

View File

@ -1,6 +1,6 @@
--- ---
id: 5cd9a70215d3c4e65518328f id: 5cd9a70215d3c4e65518328f
title: Use Recursion to Create a Countdown title: Utiliza recursión para crear una cuenta regresiva
challengeType: 1 challengeType: 1
forumTopicId: 305925 forumTopicId: 305925
dashedName: use-recursion-to-create-a-countdown dashedName: use-recursion-to-create-a-countdown
@ -8,11 +8,11 @@ dashedName: use-recursion-to-create-a-countdown
# --description-- # --description--
In a [previous challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), you learned how to use recursion to replace a for loop. Now, let's look at a more complex function that returns an array of consecutive integers starting with `1` through the number passed to the function. En el [desafío anterior](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), aprendiste como usar la recursión para reemplazar un bucle `for`. Ahora, echemos un vistazo a una función más compleja que devuelve un arreglo de enteros consecutivos empezando con `1` hasta el número pasado a la funcn.
As mentioned in the previous challenge, there will be a <dfn>base case</dfn>. The base case tells the recursive function when it no longer needs to call itself. It is a simple case where the return value is already known. There will also be a <dfn>recursive call</dfn> which executes the original function with different arguments. If the function is written correctly, eventually the base case will be reached. Como se menciona en el desafío anterior, habrá un <dfn>caso base</dfn>. El caso base le dice a la función recursiva cuando no necesita llamarse a sí misma. Es un caso simple donde el valor de retorno ya se conoce. También habrá una <dfn>llamada recursiva</dfn> la cual ejecuta la función original con argumentos diferentes. Si la función se escribe correctamente, eventualmente el caso base será alcanzado.
For example, say you want to write a recursive function that returns an array containing the numbers `1` through `n`. This function will need to accept an argument, `n`, representing the final number. Then it will need to call itself with progressively smaller values of `n` until it reaches `1`. You could write the function as follows: Por ejemplo, digamos que quieres escribir una función recursiva que devuelva un arreglo conteniendo los números `1` hasta `n`. Esta función necesitará aceptar un argumento, `n` que representa el número final. Entonces necesitará llamarse a sí misma con valores progresivamente más pequeños de `n` hasta que alcance `1`. Podrías escribir la función de la siguiente manera:
```javascript ```javascript
function countup(n) { function countup(n) {
@ -24,36 +24,38 @@ function countup(n) {
return countArray; return countArray;
} }
} }
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ] console.log(countup(5));
``` ```
At first, this seems counterintuitive since the value of `n` *decreases*, but the values in the final array are *increasing*. This happens because the push happens last, after the recursive call has returned. At the point where `n` is pushed into the array, `countup(n - 1)` has already been evaluated and returned `[1, 2, ..., n - 1]`. El valor `[1, 2, 3, 4, 5]` se mostrará en la consola.
Al principio, esto parece contraintuitivo ya que el valor de `n` *disminuye*, pero los valores en el arreglo final se están *incrementando*. Esto sucede porque la inserción ocurre al último, después de la llamada recursiva. En el punto donde `n` es empujado en el arreglo, `countup(n - 1)` ya ha sido evaluada y devuelto `[1, 2, ..., n - 1]`.
# --instructions-- # --instructions--
We have defined a function called `countdown` with one parameter (`n`). The function should use recursion to return an array containing the integers `n` through `1` based on the `n` parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with `n = 5` should return the array `[5, 4, 3, 2, 1]`. Your function must use recursion by calling itself and must not use loops of any kind. Hemos definido una función llamada `countdown` con un parámetro (`n`). La función debe usar recursión para devolver un arreglo conteniendo los `n` enteros hasta `1` basado en el parámetro `n`. Si la funcn es llamada con un número menor a 1, la función debe devolver un arreglo vacío. Por ejemplo, llamar esta función con `n = 5` debe devolver el arreglo `[5, 4, 3, 2, 1]`. Tu función debe usar recursión llamándose a sí misma y no debe usar bucles de ningún tipo.
# --hints-- # --hints--
`countdown(-1)` should return an empty array. `countdown(-1)` debe devolver un arreglo vacío.
```js ```js
assert.isEmpty(countdown(-1)); assert.isEmpty(countdown(-1));
``` ```
`countdown(10)` should return `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]` `countdown(10)` debe devolver `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`
```js ```js
assert.deepStrictEqual(countdown(10), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]); assert.deepStrictEqual(countdown(10), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
``` ```
`countdown(5)` should return `[5, 4, 3, 2, 1]` `countdown(5)` debe devolver `[5, 4, 3, 2, 1]`
```js ```js
assert.deepStrictEqual(countdown(5), [5, 4, 3, 2, 1]); assert.deepStrictEqual(countdown(5), [5, 4, 3, 2, 1]);
``` ```
Your code should not rely on any kind of loops (`for`, `while` or higher order functions such as `forEach`, `map`, `filter`, and `reduce`). Tu código no debe depender de ningún tipo de bucles (`for`, `while` o funciones de orden alto tales como `forEach`, `map`, `filter`, y `reduce`).
```js ```js
assert( assert(
@ -63,7 +65,7 @@ assert(
); );
``` ```
You should use recursion to solve this problem. Debes usar recursión para resolver este problema.
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 5cc0bd7a49b71cb96132e54c id: 5cc0bd7a49b71cb96132e54c
title: Use Recursion to Create a Range of Numbers title: Usa recursión para crear un rango de números
challengeType: 1 challengeType: 1
forumTopicId: 301180 forumTopicId: 301180
dashedName: use-recursion-to-create-a-range-of-numbers dashedName: use-recursion-to-create-a-range-of-numbers
@ -8,21 +8,21 @@ dashedName: use-recursion-to-create-a-range-of-numbers
# --description-- # --description--
Continuing from the previous challenge, we provide you another opportunity to create a recursive function to solve a problem. Continuando con el desafío anterior, te ofrecemos otra oportunidad de crear una función recursiva para resolver un problema.
# --instructions-- # --instructions--
We have defined a function named `rangeOfNumbers` with two parameters. The function should return an array of integers which begins with a number represented by the `startNum` parameter and ends with a number represented by the `endNum` parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both `startNum` and `endNum` are the same. Hemos definido una función llamada `rangeOfNumbers` con dos parámetros. La función debe devolver un arreglo de enteros que comienza con el número representado por el parámetro `startNum` y termina con el número representado por el parámetro `endNum`. El número inicial será siempre menor o igual que el número final. Tu función debe utilizar recursión, llamándose a sí misma, y no utilizar bucles de ningún tipo. También debe funcionar en el caso que `startNum` y `endNum` sean iguales.
# --hints-- # --hints--
Your function should return an array. Tu función debe devolver un arreglo.
```js ```js
assert(Array.isArray(rangeOfNumbers(5, 10))); assert(Array.isArray(rangeOfNumbers(5, 10)));
``` ```
Your code should not use any loop syntax (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`). Tu código no debe utilizar bucles (`for`, `while` o funciones de orden superior como `forEach`, `map`, `filter`, o `reduce`).
```js ```js
assert( assert(
@ -32,7 +32,7 @@ assert(
); );
``` ```
`rangeOfNumbers` should use recursion (call itself) to solve this challenge. `rangeOfNumbers` debe utilizar recursión (llamadas a sí mismo) para resolver este desafío.
```js ```js
assert( assert(
@ -42,19 +42,19 @@ assert(
); );
``` ```
`rangeOfNumbers(1, 5)` should return `[1, 2, 3, 4, 5]`. `rangeOfNumbers(1, 5)` debe devolver `[1, 2, 3, 4, 5]`.
```js ```js
assert.deepStrictEqual(rangeOfNumbers(1, 5), [1, 2, 3, 4, 5]); assert.deepStrictEqual(rangeOfNumbers(1, 5), [1, 2, 3, 4, 5]);
``` ```
`rangeOfNumbers(6, 9)` should return `[6, 7, 8, 9]`. `rangeOfNumbers(6, 9)` debe devolver `[6, 7, 8, 9]`.
```js ```js
assert.deepStrictEqual(rangeOfNumbers(6, 9), [6, 7, 8, 9]); assert.deepStrictEqual(rangeOfNumbers(6, 9), [6, 7, 8, 9]);
``` ```
`rangeOfNumbers(4, 4)` should return `[4]`. `rangeOfNumbers(4, 4)` debe devolver `[4]`.
```js ```js
assert.deepStrictEqual(rangeOfNumbers(4, 4), [4]); assert.deepStrictEqual(rangeOfNumbers(4, 4), [4]);

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b7e367417b2b2512b24 id: 587d7b7e367417b2b2512b24
title: Use the Conditional (Ternary) Operator title: Usa el operador condicional (ternario)
challengeType: 1 challengeType: 1
forumTopicId: 301181 forumTopicId: 301181
dashedName: use-the-conditional-ternary-operator dashedName: use-the-conditional-ternary-operator
@ -8,13 +8,11 @@ dashedName: use-the-conditional-ternary-operator
# --description-- # --description--
The <dfn>conditional operator</dfn>, also called the <dfn>ternary operator</dfn>, can be used as a one line if-else expression. El <dfn>operador condicional</dfn>, también llamado el <dfn>operador ternario</dfn>, puede utilizarse como una expresión if-else de una sola línea.
The syntax is: La sintaxis es `a ? b : c`, donde `a` es la condición, `b` es el código a ejecutar cuando la condición devuelve `true`, y `c` es el código a ejecutar cuando la condición devuelve `false`.
`condition ? expression-if-true : expression-if-false;` La siguiente función utiliza una sentencia `if/else` para comprobar una condición:
The following function uses an if-else statement to check a condition:
```js ```js
function findGreater(a, b) { function findGreater(a, b) {
@ -27,7 +25,7 @@ function findGreater(a, b) {
} }
``` ```
This can be re-written using the `conditional operator`: Esto puede reescribirse usando el operador condicional:
```js ```js
function findGreater(a, b) { function findGreater(a, b) {
@ -37,29 +35,29 @@ function findGreater(a, b) {
# --instructions-- # --instructions--
Use the `conditional operator` in the `checkEqual` function to check if two numbers are equal or not. The function should return either "Equal" or "Not Equal". Utiliza el operador condicional en la función `checkEqual` para comprobar si dos números son iguales o no. La función debe devolver la cadena `Equal` o la cadena `Not Equal`.
# --hints-- # --hints--
`checkEqual` should use the `conditional operator` `checkEqual` debe usar el operador condicional
```js ```js
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code)); assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code));
``` ```
`checkEqual(1, 2)` should return "Not Equal" `checkEqual(1, 2)` debe devolver la cadena `Not Equal`
```js ```js
assert(checkEqual(1, 2) === 'Not Equal'); assert(checkEqual(1, 2) === 'Not Equal');
``` ```
`checkEqual(1, 1)` should return "Equal" `checkEqual(1, 1)` debe devolver la cadena `Equal`
```js ```js
assert(checkEqual(1, 1) === 'Equal'); assert(checkEqual(1, 1) === 'Equal');
``` ```
`checkEqual(1, -1)` should return "Not Equal" `checkEqual(1, -1)` debe devolver la cadena `Not Equal`
```js ```js
assert(checkEqual(1, -1) === 'Not Equal'); assert(checkEqual(1, -1) === 'Not Equal');

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b7e367417b2b2512b22 id: 587d7b7e367417b2b2512b22
title: Use the parseInt Function with a Radix title: Utiliza la función "parseInt" con Radix (Base)
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/c6K4Kh3' videoUrl: 'https://scrimba.com/c/c6K4Kh3'
forumTopicId: 301182 forumTopicId: 301182
@ -9,49 +9,49 @@ dashedName: use-the-parseint-function-with-a-radix
# --description-- # --description--
The `parseInt()` function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36. La función `parseInt()` analiza una cadena y devuelve un entero. Recibe un segundo argumento para la base (radix), que especifica la base del número representado en la cadena. La base (radix) puede ser un número entero entre 2 y 36.
The function call looks like: La llamada a la función se realiza de la siguiente manera:
`parseInt(string, radix);` `parseInt(string, radix);`
And here's an example: A continuación, te presentamos un ejemplo:
`var a = parseInt("11", 2);` `var a = parseInt("11", 2);`
The radix variable says that "11" is in the binary system, or base 2. This example converts the string "11" to an integer 3. La variable radix indica que `11` está en el sistema binario, o base 2. Este ejemplo convierte la cadena `11` a un entero `3`.
# --instructions-- # --instructions--
Use `parseInt()` in the `convertToInteger` function so it converts a binary number to an integer and returns it. Utiliza `parseInt()` dentro de la función `convertToInteger` para convertir un número binario en un número entero, y devuélvelo.
# --hints-- # --hints--
`convertToInteger` should use the `parseInt()` function `convertToInteger` debe utilizar la función `parseInt()`
```js ```js
assert(/parseInt/g.test(code)); assert(/parseInt/g.test(code));
``` ```
`convertToInteger("10011")` should return a number `convertToInteger("10011")` debe devolver un número
```js ```js
assert(typeof convertToInteger('10011') === 'number'); assert(typeof convertToInteger('10011') === 'number');
``` ```
`convertToInteger("10011")` should return 19 `convertToInteger("10011")` debe devolver 19
```js ```js
assert(convertToInteger('10011') === 19); assert(convertToInteger('10011') === 19);
``` ```
`convertToInteger("111001")` should return 57 `convertToInteger("111001")` debe devolver 57
```js ```js
assert(convertToInteger('111001') === 57); assert(convertToInteger('111001') === 57);
``` ```
`convertToInteger("JamesBond")` should return NaN `convertToInteger("JamesBond")` debe devolver `NaN`
```js ```js
assert.isNaN(convertToInteger('JamesBond')); assert.isNaN(convertToInteger('JamesBond'));

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7b7e367417b2b2512b23 id: 587d7b7e367417b2b2512b23
title: Use the parseInt Function title: Utiliza la función "parseInt"
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cm83LSW' videoUrl: 'https://scrimba.com/c/cm83LSW'
forumTopicId: 301183 forumTopicId: 301183
@ -9,43 +9,43 @@ dashedName: use-the-parseint-function
# --description-- # --description--
The `parseInt()` function parses a string and returns an integer. Here's an example: La función `parseInt()` analiza una cadena y devuelve un entero. A continuación, te presentamos un ejemplo:
`var a = parseInt("007");` `var a = parseInt("007");`
The above function converts the string "007" to an integer 7. If the first character in the string can't be converted into a number, then it returns `NaN`. La función anterior convierte la cadena `007` al entero `7`. Si el primer carácter de la cadena no puede ser convertido en un número, entonces devuelve `NaN`.
# --instructions-- # --instructions--
Use `parseInt()` in the `convertToInteger` function so it converts the input string `str` into an integer, and returns it. Utiliza `parseInt()` en la función `convertToInteger` para convertir la cadena de entrada `str` a un número entero, y devuélvelo.
# --hints-- # --hints--
`convertToInteger` should use the `parseInt()` function `convertToInteger` debe utilizar la función `parseInt()`
```js ```js
assert(/parseInt/g.test(code)); assert(/parseInt/g.test(code));
``` ```
`convertToInteger("56")` should return a number `convertToInteger("56")` debe devolver un número
```js ```js
assert(typeof convertToInteger('56') === 'number'); assert(typeof convertToInteger('56') === 'number');
``` ```
`convertToInteger("56")` should return 56 `convertToInteger("56")` debe devolver 56
```js ```js
assert(convertToInteger('56') === 56); assert(convertToInteger('56') === 56);
``` ```
`convertToInteger("77")` should return 77 `convertToInteger("77")` debe devolver 77
```js ```js
assert(convertToInteger('77') === 77); assert(convertToInteger('77') === 77);
``` ```
`convertToInteger("JamesBond")` should return NaN `convertToInteger("JamesBond")` debe devolver `NaN`
```js ```js
assert.isNaN(convertToInteger('JamesBond')); assert.isNaN(convertToInteger('JamesBond'));

View File

@ -1,6 +1,6 @@
--- ---
id: 56533eb9ac21ba0edf2244ca id: 56533eb9ac21ba0edf2244ca
title: Using Objects for Lookups title: Usa objetos para hacer búsquedas
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cdBk8sM' videoUrl: 'https://scrimba.com/c/cdBk8sM'
forumTopicId: 18373 forumTopicId: 18373
@ -9,9 +9,9 @@ dashedName: using-objects-for-lookups
# --description-- # --description--
Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to "lookup" values rather than a `switch` statement or an `if/else` chain. This is most useful when you know that your input data is limited to a certain range. Los objetos pueden ser considerados como un almacenamiento clave/valor, como un diccionario. Si tienes datos tabulares, puedes utilizar un objeto para hacer una búsqueda de valores en lugar de una declaración `switch` o encadenar `if/else`. Esto es de mucha utilidad cuando se sabe que los datos de entrada están limitados a un cierto rango.
Here is an example of a simple reverse alphabet lookup: Aquí hay un ejemplo de una simple búsqueda de alfabeto inverso:
```js ```js
var alpha = { var alpha = {
@ -24,68 +24,70 @@ var alpha = {
25:"B", 25:"B",
26:"A" 26:"A"
}; };
alpha[2]; // "Y" alpha[2];
alpha[24]; // "C" alpha[24];
var value = 2; var value = 2;
alpha[value]; // "Y" alpha[value];
``` ```
`alpha[2]` es la cadena `Y`, `alpha[24]` es la cadena `C`, y `alpha[value]` es la cadena `Y`.
# --instructions-- # --instructions--
Convert the switch statement into an object called `lookup`. Use it to look up `val` and assign the associated string to the `result` variable. Convierte la declaración switch en un objeto llamado `lookup`. Úsalo para buscar `val` y asignar la cadena asociada a la variable `result`.
# --hints-- # --hints--
`phoneticLookup("alpha")` should equal `"Adams"` `phoneticLookup("alpha")` debe ser igual a la cadena `Adams`
```js ```js
assert(phoneticLookup('alpha') === 'Adams'); assert(phoneticLookup('alpha') === 'Adams');
``` ```
`phoneticLookup("bravo")` should equal `"Boston"` `phoneticLookup("bravo")` debe ser igual a la cadena `Boston`
```js ```js
assert(phoneticLookup('bravo') === 'Boston'); assert(phoneticLookup('bravo') === 'Boston');
``` ```
`phoneticLookup("charlie")` should equal `"Chicago"` `phoneticLookup("charlie")` debe ser igual a la cadena `Chicago`
```js ```js
assert(phoneticLookup('charlie') === 'Chicago'); assert(phoneticLookup('charlie') === 'Chicago');
``` ```
`phoneticLookup("delta")` should equal `"Denver"` `phoneticLookup("delta")` debe ser igual a la cadena `Denver`
```js ```js
assert(phoneticLookup('delta') === 'Denver'); assert(phoneticLookup('delta') === 'Denver');
``` ```
`phoneticLookup("echo")` should equal `"Easy"` `phoneticLookup("echo")` debe ser igual a la cadena `Easy`
```js ```js
assert(phoneticLookup('echo') === 'Easy'); assert(phoneticLookup('echo') === 'Easy');
``` ```
`phoneticLookup("foxtrot")` should equal `"Frank"` `phoneticLookup("foxtrot")` debe ser igual a la cadena `Frank`
```js ```js
assert(phoneticLookup('foxtrot') === 'Frank'); assert(phoneticLookup('foxtrot') === 'Frank');
``` ```
`phoneticLookup("")` should equal `undefined` `phoneticLookup("")` debe ser igual a `undefined`
```js ```js
assert(typeof phoneticLookup('') === 'undefined'); assert(typeof phoneticLookup('') === 'undefined');
``` ```
You should not modify the `return` statement No debes modificar la sentencia `return`
```js ```js
assert(code.match(/return\sresult;/)); assert(code.match(/return\sresult;/));
``` ```
You should not use `case`, `switch`, or `if` statements No debes usar sentencias `case`, `switch`o `if`
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 56bbb991ad1ed5201cd392cf id: 56bbb991ad1ed5201cd392cf
title: Write Reusable JavaScript with Functions title: Escribe JavaScript reutilizable utilizando funciones
challengeType: 1 challengeType: 1
videoUrl: 'https://scrimba.com/c/cL6dqfy' videoUrl: 'https://scrimba.com/c/cL6dqfy'
forumTopicId: 18378 forumTopicId: 18378
@ -9,9 +9,9 @@ dashedName: write-reusable-javascript-with-functions
# --description-- # --description--
In JavaScript, we can divide up our code into reusable parts called <dfn>functions</dfn>. En JavaScript, podemos dividir nuestro código en partes reutilizables llamadas <dfn>funciones</dfn>.
Here's an example of a function: Este es un ejemplo de una funcn:
```js ```js
function functionName() { function functionName() {
@ -19,27 +19,27 @@ function functionName() {
} }
``` ```
You can call or <dfn>invoke</dfn> this function by using its name followed by parentheses, like this: `functionName();` Each time the function is called it will print out the message `"Hello World"` on the dev console. All of the code between the curly braces will be executed every time the function is called. Puedes llamar o <dfn>invocar</dfn> esta función usando su nombre seguido por paréntesis, así: `functionName();` Cada vez que se llame la función se imprimirá el mensaje `Hello World` en la consola de desarrollo. Todo el código entre las llaves se ejecutará cada vez que se llame la función.
# --instructions-- # --instructions--
<ol><li>Create a function called <code>reusableFunction</code> which prints <code>"Hi World"</code> to the dev console.</li><li>Call the function.</li></ol> <ol><li>Crea una función llamada <code>reusableFunction</code> que imprima <code>"Hi World"</code> en la consola de desarrollo.</li><li>Llama a la funcn.</li></ol>
# --hints-- # --hints--
`reusableFunction` should be a function. `reusableFunction` debe ser una funcn.
```js ```js
assert(typeof reusableFunction === 'function'); assert(typeof reusableFunction === 'function');
``` ```
`reusableFunction` should output "Hi World" to the dev console. `reusableFunction` debe mostrar la cadena `Hi World` en la consola.
```js ```js
assert(hiWorldWasLogged); assert(hiWorldWasLogged);
``` ```
You should call `reusableFunction` after you define it. Debes llamar `reusableFunction` después de definirla.
```js ```js
assert(/^\s*reusableFunction\(\)\s*/m.test(code)); assert(/^\s*reusableFunction\(\)\s*/m.test(code));
@ -87,7 +87,9 @@ if (typeof reusableFunction !== "function") {
``` ```
## --seed-contents-- ## --seed-contents--
```js ```js
``` ```
# --solutions-- # --solutions--