docs: add Spanish docs
This commit is contained in:
@ -0,0 +1,83 @@
|
||||
---
|
||||
id: a77dbc43c33f39daa4429b4f
|
||||
title: Boo who
|
||||
localeTitle: Boo quien
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Compruebe si un valor está clasificado como un primitivo booleano. Devuelve verdadero o falso.
|
||||
Los primitivos booleanos son verdaderos y falsos.
|
||||
Recuerda usar <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> si te atascas. Trate de emparejar el programa. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>booWho(true)</code> debe devolver true.
|
||||
testString: 'assert.strictEqual(booWho(true), true, "<code>booWho(true)</code> should return true.");'
|
||||
- text: <code>booWho(false)</code> debe devolver verdadero.
|
||||
testString: 'assert.strictEqual(booWho(false), true, "<code>booWho(false)</code> should return true.");'
|
||||
- text: ' <code>booWho([1, 2, 3])</code> debe devolver falso.'
|
||||
testString: 'assert.strictEqual(booWho([1, 2, 3]), false, "<code>booWho([1, 2, 3])</code> should return false.");'
|
||||
- text: ' <code>booWho([].slice)</code> debe devolver falso.'
|
||||
testString: 'assert.strictEqual(booWho([].slice), false, "<code>booWho([].slice)</code> should return false.");'
|
||||
- text: ' <code>booWho({ "a": 1 })</code> debe devolver falso.'
|
||||
testString: 'assert.strictEqual(booWho({ "a": 1 }), false, "<code>booWho({ "a": 1 })</code> should return false.");'
|
||||
- text: <code>booWho(1)</code> debe devolver falso.
|
||||
testString: 'assert.strictEqual(booWho(1), false, "<code>booWho(1)</code> should return false.");'
|
||||
- text: <code>booWho(NaN)</code> debe devolver falso.
|
||||
testString: 'assert.strictEqual(booWho(NaN), false, "<code>booWho(NaN)</code> should return false.");'
|
||||
- text: <code>booWho("a")</code> debe devolver falso.
|
||||
testString: 'assert.strictEqual(booWho("a"), false, "<code>booWho("a")</code> should return false.");'
|
||||
- text: <code>booWho("true")</code> debería devolver falso.
|
||||
testString: 'assert.strictEqual(booWho("true"), false, "<code>booWho("true")</code> should return false.");'
|
||||
- text: <code>booWho("false")</code> debe devolver false.
|
||||
testString: 'assert.strictEqual(booWho("false"), false, "<code>booWho("false")</code> should return false.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function booWho(bool) {
|
||||
// What is the new fad diet for ghost developers? The Boolean.
|
||||
return bool;
|
||||
}
|
||||
|
||||
booWho(null);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function booWho(bool) {
|
||||
return typeof bool === "boolean";
|
||||
}
|
||||
|
||||
booWho(null);
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,83 @@
|
||||
---
|
||||
id: a9bd25c716030ec90084d8a1
|
||||
title: Chunky Monkey
|
||||
localeTitle: Mono grueso
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Escriba una función que divida una matriz (primer argumento) en grupos de la longitud del <code>size</code> (segundo argumento) y los devuelva como una matriz bidimensional.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>chunkArrayInGroups(["a", "b", "c", "d"], 2)</code> debe devolver <code>[["a", "b"], ["c", "d"]]</code> .'
|
||||
testString: 'assert.deepEqual(chunkArrayInGroups(["a", "b", "c", "d"], 2), [["a", "b"], ["c", "d"]], "<code>chunkArrayInGroups(["a", "b", "c", "d"], 2)</code> should return <code>[["a", "b"], ["c", "d"]]</code>.");'
|
||||
- text: ' <code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)</code> debe devolver <code>[[0, 1, 2], [3, 4, 5]]</code> .'
|
||||
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [[0, 1, 2], [3, 4, 5]], "<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)</code> should return <code>[[0, 1, 2], [3, 4, 5]]</code>.");'
|
||||
- text: ' <code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)</code> debe devolver <code>[[0, 1], [2, 3], [4, 5]]</code> .'
|
||||
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [[0, 1], [2, 3], [4, 5]], "<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)</code> should return <code>[[0, 1], [2, 3], [4, 5]]</code>.");'
|
||||
- text: ' <code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)</code> debe devolver <code>[[0, 1, 2, 3], [4, 5]]</code> .'
|
||||
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [[0, 1, 2, 3], [4, 5]], "<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)</code> should return <code>[[0, 1, 2, 3], [4, 5]]</code>.");'
|
||||
- text: ' <code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)</code> debe devolver <code>[[0, 1, 2], [3, 4, 5], [6]]</code> .'
|
||||
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [[0, 1, 2], [3, 4, 5], [6]], "<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)</code> should return <code>[[0, 1, 2], [3, 4, 5], [6]]</code>.");'
|
||||
- text: ' <code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)</code> debe devolver <code>[[0, 1, 2, 3], [4, 5, 6, 7], [8]]</code> . '
|
||||
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [[0, 1, 2, 3], [4, 5, 6, 7], [8]], "<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)</code> should return <code>[[0, 1, 2, 3], [4, 5, 6, 7], [8]]</code>.");'
|
||||
- text: ' <code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)</code> debe devolver <code>[[0, 1], [2, 3], [4, 5], [6, 7], [8]]</code> .
|
||||
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [[0, 1], [2, 3], [4, 5], [6, 7], [8]], "<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)</code> should return <code>[[0, 1], [2, 3], [4, 5], [6, 7], [8]]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function chunkArrayInGroups(arr, size) {
|
||||
// Break it up.
|
||||
return arr;
|
||||
}
|
||||
|
||||
chunkArrayInGroups(["a", "b", "c", "d"], 2);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function chunkArrayInGroups(arr, size) {
|
||||
let out = [];
|
||||
|
||||
for (let i = 0; i < arr.length; i += size) {
|
||||
out.push(arr.slice(i, i + size));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
chunkArrayInGroups(["a", "b", "c", "d"], 2);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: acda2fb1324d9b0fa741e6b5
|
||||
title: Confirm the Ending
|
||||
localeTitle: Confirmar el final
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Compruebe si una cadena (primer argumento, <code>str</code> ) termina con la cadena de destino dada (segundo argumento, <code>target</code> ).
|
||||
Este desafío <em>se</em> puede resolver con el método <code>.endsWith()</code> , que se introdujo en ES2015. Pero para el propósito de este desafío, nos gustaría que utilices uno de los métodos de subcadena de JavaScript.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>confirmEnding("Bastian", "n")</code> debe devolver verdadero.'
|
||||
testString: 'assert(confirmEnding("Bastian", "n") === true, "<code>confirmEnding("Bastian", "n")</code> should return true.");'
|
||||
- text: ' <code>confirmEnding("Congratulation", "on")</code> debe devolver verdadero.'
|
||||
testString: 'assert(confirmEnding("Congratulation", "on") === true, "<code>confirmEnding("Congratulation", "on")</code> should return true.");'
|
||||
- text: ' <code>confirmEnding("Connor", "n")</code> debe devolver falso.'
|
||||
testString: 'assert(confirmEnding("Connor", "n") === false, "<code>confirmEnding("Connor", "n")</code> should return false.");'
|
||||
- text: ' <code>confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")</code> debe devolver falso.
|
||||
testString: 'assert(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") === false, "<code>confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")</code> should return false.");'
|
||||
- text: ' <code>confirmEnding("He has to give me a new name", "name")</code> debe devolver verdadero.'
|
||||
testString: 'assert(confirmEnding("He has to give me a new name", "name") === true, "<code>confirmEnding("He has to give me a new name", "name")</code> should return true.");'
|
||||
- text: ' <code>confirmEnding("Open sesame", "same")</code> debe devolver verdadero.'
|
||||
testString: 'assert(confirmEnding("Open sesame", "same") === true, "<code>confirmEnding("Open sesame", "same")</code> should return true.");'
|
||||
- text: ' <code>confirmEnding("Open sesame", "pen")</code> debe devolver falso.
|
||||
testString: 'assert(confirmEnding("Open sesame", "pen") === false, "<code>confirmEnding("Open sesame", "pen")</code> should return false.");'
|
||||
- text: ' <code>confirmEnding("Open sesame", "game")</code> debe devolver falso.
|
||||
testString: 'assert(confirmEnding("Open sesame", "game") === false, "<code>confirmEnding("Open sesame", "game")</code> should return false.");'
|
||||
- text: ' <code>confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")</code> debería devolver el valor falso ".
|
||||
testString: 'assert(confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") === false, "<code>confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")</code> should return false.");'
|
||||
- text: ' <code>confirmEnding("Abstraction", "action")</code> debe devolver verdadero.'
|
||||
testString: 'assert(confirmEnding("Abstraction", "action") === true, "<code>confirmEnding("Abstraction", "action")</code> should return true.");'
|
||||
- text: No use el método <code>.endsWith()</code> para resolver el desafío.
|
||||
testString: 'assert(!(/\.endsWith\(.*?\)\s*?;?/.test(code)) && !(/\["endsWith"\]/.test(code)), "Do not use the built-in method <code>.endsWith()</code> to solve the challenge.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function confirmEnding(str, target) {
|
||||
// "Never give up and good luck will find you."
|
||||
// -- Falcor
|
||||
return str;
|
||||
}
|
||||
|
||||
confirmEnding("Bastian", "n");
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function confirmEnding(str, target) {
|
||||
return str.substring(str.length - target.length) === target;
|
||||
}
|
||||
|
||||
confirmEnding("Bastian", "n");
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b3
|
||||
title: Convert Celsius to Fahrenheit
|
||||
localeTitle: Convertir Celsius a Fahrenheit
|
||||
challengeType: 1
|
||||
isRequired: true
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El algoritmo para convertir de Celsius a Fahrenheit es la temperatura en grados Celsius <code>9/5</code> , más <code>32</code> .
|
||||
Se le da una variable <code>celsius</code> representa una temperatura en grados centígrados. Use la variable <code>fahrenheit</code> ya definida y asígnele la temperatura Fahrenheit equivalente a la temperatura Celsius dada. Use el algoritmo mencionado anteriormente para ayudar a convertir la temperatura en grados Celsius a Fahrenheit.
|
||||
No se preocupe demasiado por la función y las declaraciones de devolución, ya que se cubrirán en futuros desafíos. Por ahora, solo utiliza operadores que ya hayas aprendido.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>convertToF(0)</code> debe devolver un número
|
||||
testString: 'assert(typeof convertToF(0) === "number", "<code>convertToF(0)</code> should return a number");'
|
||||
- text: <code>convertToF(-30)</code> debe devolver un valor de <code>-22</code>
|
||||
testString: 'assert(convertToF(-30) === -22, "<code>convertToF(-30)</code> should return a value of <code>-22</code>");'
|
||||
- text: <code>convertToF(-10)</code> debe devolver un valor de <code>14</code>
|
||||
testString: 'assert(convertToF(-10) === 14, "<code>convertToF(-10)</code> should return a value of <code>14</code>");'
|
||||
- text: <code>convertToF(0)</code> debe devolver un valor de <code>32</code>
|
||||
testString: 'assert(convertToF(0) === 32, "<code>convertToF(0)</code> should return a value of <code>32</code>");'
|
||||
- text: <code>convertToF(20)</code> debe devolver un valor de <code>68</code>
|
||||
testString: 'assert(convertToF(20) === 68, "<code>convertToF(20)</code> should return a value of <code>68</code>");'
|
||||
- text: <code>convertToF(30)</code> debe devolver un valor de <code>86</code>
|
||||
testString: 'assert(convertToF(30) === 86, "<code>convertToF(30)</code> should return a value of <code>86</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function convertToF(celsius) {
|
||||
let fahrenheit;
|
||||
return fahrenheit;
|
||||
}
|
||||
|
||||
convertToF(30);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function convertToF(celsius) {
|
||||
let fahrenheit = celsius * 9/5 + 32;
|
||||
|
||||
return fahrenheit;
|
||||
}
|
||||
|
||||
convertToF(30);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: a302f7aae1aa3152a5b413bc
|
||||
title: Factorialize a Number
|
||||
localeTitle: Factorializar un número
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Devuelve el factorial del entero proporcionado.
|
||||
Si el entero se representa con la letra n, un factorial es el producto de todos los enteros positivos menores o iguales a n.
|
||||
factoriales a menudo se representan con la notación abreviada <code>n!</code>
|
||||
Por ejemplo: <code>5! = 1 * 2 * 3 * 4 * 5 = 120</code>
|
||||
Solo se proporcionarán a la función números enteros mayores o iguales a cero.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>factorialize(5)</code> debe devolver un número.
|
||||
testString: 'assert(typeof factorialize(5) === "number", "<code>factorialize(5)</code> should return a number.");'
|
||||
- text: <code>factorialize(5)</code> debe devolver 120.
|
||||
testString: 'assert(factorialize(5) === 120, "<code>factorialize(5)</code> should return 120.");'
|
||||
- text: <code>factorialize(10)</code> debe devolver 3628800.
|
||||
testString: 'assert(factorialize(10) === 3628800, "<code>factorialize(10)</code> should return 3628800.");'
|
||||
- text: <code>factorialize(20)</code> debe devolver 2432902008176640000.
|
||||
testString: 'assert(factorialize(20) === 2432902008176640000, "<code>factorialize(20)</code> should return 2432902008176640000.");'
|
||||
- text: <code>factorialize(0)</code> debe devolver 1.
|
||||
testString: 'assert(factorialize(0) === 1, "<code>factorialize(0)</code> should return 1.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function factorialize(num) {
|
||||
return num;
|
||||
}
|
||||
|
||||
factorialize(5);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function factorialize(num) {
|
||||
return num < 1 ? 1 : num * factorialize(num - 1);
|
||||
}
|
||||
|
||||
factorialize(5);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: adf08ec01beb4f99fc7a68f2
|
||||
title: Falsy Bouncer
|
||||
localeTitle: Falsy Bouncer
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Eliminar todos los valores falsos de una matriz.
|
||||
valores de <code>false</code> en JavaScript son <code>false</code> , <code>null</code> , <code>0</code> , <code>""</code> , <code>undefined</code> y <code>NaN</code> .
|
||||
Sugerencia: intente convertir cada valor a un booleano.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>bouncer([7, "ate", "", false, 9])</code> debe devolver <code>[7, "ate", 9]</code> .'
|
||||
testString: 'assert.deepEqual(bouncer([7, "ate", "", false, 9]), [7, "ate", 9], "<code>bouncer([7, "ate", "", false, 9])</code> should return <code>[7, "ate", 9]</code>.");'
|
||||
- text: ' <code>bouncer(["a", "b", "c"])</code> debe devolver <code>["a", "b", "c"]</code> .'
|
||||
testString: 'assert.deepEqual(bouncer(["a", "b", "c"]), ["a", "b", "c"], "<code>bouncer(["a", "b", "c"])</code> should return <code>["a", "b", "c"]</code>.");'
|
||||
- text: ' <code>bouncer([false, null, 0, NaN, undefined, ""])</code> debe devolver <code>[]</code> .'
|
||||
testString: 'assert.deepEqual(bouncer([false, null, 0, NaN, undefined, ""]), [], "<code>bouncer([false, null, 0, NaN, undefined, ""])</code> should return <code>[]</code>.");'
|
||||
- text: ' <code>bouncer([1, null, NaN, 2, undefined])</code> debe devolver <code>[1, 2]</code> .'
|
||||
testString: 'assert.deepEqual(bouncer([1, null, NaN, 2, undefined]), [1, 2], "<code>bouncer([1, null, NaN, 2, undefined])</code> should return <code>[1, 2]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function bouncer(arr) {
|
||||
// Don't show a false ID to this bouncer.
|
||||
return arr;
|
||||
}
|
||||
|
||||
bouncer([7, "ate", "", false, 9]);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function bouncer(arr) {
|
||||
return arr.filter(e => e);
|
||||
}
|
||||
|
||||
bouncer([7, "ate", "", false, 9]);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: a26cbbe9ad8655a977e1ceb5
|
||||
title: Find the Longest Word in a String
|
||||
localeTitle: Encuentra la palabra más larga en una cadena
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Devuelve la longitud de la palabra más larga en la oración provista.
|
||||
Tu respuesta debe ser un número.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> debería devolver un número.
|
||||
testString: 'assert(typeof findLongestWordLength("The quick brown fox jumped over the lazy dog") === "number", "<code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return a number.");'
|
||||
- text: <code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> debería devolver 6.
|
||||
testString: 'assert(findLongestWordLength("The quick brown fox jumped over the lazy dog") === 6, "<code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return 6.");'
|
||||
- text: <code>findLongestWordLength("May the force be with you")</code> debe devolver 5.
|
||||
testString: 'assert(findLongestWordLength("May the force be with you") === 5, "<code>findLongestWordLength("May the force be with you")</code> should return 5.");'
|
||||
- text: <code>findLongestWordLength("Google do a barrel roll")</code> debe devolver 6.
|
||||
testString: 'assert(findLongestWordLength("Google do a barrel roll") === 6, "<code>findLongestWordLength("Google do a barrel roll")</code> should return 6.");'
|
||||
- text: <code>findLongestWordLength("What is the average airspeed velocity of an unladen swallow")</code> debe devolver 8.
|
||||
testString: 'assert(findLongestWordLength("What is the average airspeed velocity of an unladen swallow") === 8, "<code>findLongestWordLength("What is the average airspeed velocity of an unladen swallow")</code> should return 8.");'
|
||||
- text: <code>findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")</code> debería devolver 19.
|
||||
testString: 'assert(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") === 19, "<code>findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")</code> should return 19.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function findLongestWordLength(str) {
|
||||
return str.length;
|
||||
}
|
||||
|
||||
findLongestWordLength("The quick brown fox jumped over the lazy dog");
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function findLongestWordLength(str) {
|
||||
return str.split(' ').sort((a, b) => b.length - a.length)[0].length;
|
||||
}
|
||||
|
||||
findLongestWordLength("The quick brown fox jumped over the lazy dog");
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: a6e40f1041b06c996f7b2406
|
||||
title: Finders Keepers
|
||||
localeTitle: Buscadores guardianes
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Cree una función que examine una matriz (primer argumento) y devuelva el primer elemento de la matriz que pase una prueba de verdad (segundo argumento). Si ningún elemento pasa la prueba, devuelva indefinido.
|
||||
Recuerda usar <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> si te atascas. Trate de emparejar el programa. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })</code> debe devolver 8.'
|
||||
testString: 'assert.strictEqual(findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }), 8, "<code>findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })</code> should return 8.");'
|
||||
- text: ' <code>findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })</code> debe devolver undefined.'
|
||||
testString: 'assert.strictEqual(findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }), undefined, "<code>findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })</code> should return undefined.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function findElement(arr, func) {
|
||||
let num = 0;
|
||||
return num;
|
||||
}
|
||||
|
||||
findElement([1, 2, 3, 4], num => num % 2 === 0);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function findElement(arr, func) {
|
||||
let num;
|
||||
|
||||
arr.some(e => {
|
||||
if (func(e)) {
|
||||
num = e;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
return num;
|
||||
}
|
||||
|
||||
findElement([1, 2, 3, 4], num => num % 2 === 0);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: af2170cad53daa0770fabdea
|
||||
title: Mutations
|
||||
localeTitle: Mutaciones
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Devuelva verdadero si la cadena en el primer elemento de la matriz contiene todas las letras de la cadena en el segundo elemento de la matriz.
|
||||
Por ejemplo, <code>["hello", "Hello"]</code> , debería devolver verdadero porque todas las letras en la segunda cadena están presentes en el primer caso, ignorando el caso.
|
||||
Los argumentos <code>["hello", "hey"]</code> deben devolver falso porque la cadena "hola" no contiene una "y".
|
||||
Por último, <code>["Alien", "line"]</code> , debe devolver verdadero porque todas las letras en "line" están presentes en "Alien".
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>mutation(["hello", "hey"])</code> debe devolver falso.'
|
||||
testString: 'assert(mutation(["hello", "hey"]) === false, "<code>mutation(["hello", "hey"])</code> should return false.");'
|
||||
- text: ' <code>mutation(["hello", "Hello"])</code> debe devolver verdadero.'
|
||||
testString: 'assert(mutation(["hello", "Hello"]) === true, "<code>mutation(["hello", "Hello"])</code> should return true.");'
|
||||
- text: ' <code>mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])</code> debe devolver verdadero.'
|
||||
testString: 'assert(mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"]) === true, "<code>mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])</code> should return true.");'
|
||||
- text: 'la <code>mutation(["Mary", "Army"])</code> debería devolver la verdad.'
|
||||
testString: 'assert(mutation(["Mary", "Army"]) === true, "<code>mutation(["Mary", "Army"])</code> should return true.");'
|
||||
- text: 'la <code>mutation(["Mary", "Aarmy"])</code> debe devolver la verdad.'
|
||||
testString: 'assert(mutation(["Mary", "Aarmy"]) === true, "<code>mutation(["Mary", "Aarmy"])</code> should return true.");'
|
||||
- text: ' <code>mutation(["Alien", "line"])</code> debe devolver true.'
|
||||
testString: 'assert(mutation(["Alien", "line"]) === true, "<code>mutation(["Alien", "line"])</code> should return true.");'
|
||||
- text: ' <code>mutation(["floor", "for"])</code> debe devolver verdadero.'
|
||||
testString: 'assert(mutation(["floor", "for"]) === true, "<code>mutation(["floor", "for"])</code> should return true.");'
|
||||
- text: ' <code>mutation(["hello", "neo"])</code> debe devolver falso.'
|
||||
testString: 'assert(mutation(["hello", "neo"]) === false, "<code>mutation(["hello", "neo"])</code> should return false.");'
|
||||
- text: ' <code>mutation(["voodoo", "no"])</code> debe devolver falso.'
|
||||
testString: 'assert(mutation(["voodoo", "no"]) === false, "<code>mutation(["voodoo", "no"])</code> should return false.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function mutation(arr) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
mutation(["hello", "hey"]);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function mutation(arr) {
|
||||
let hash = Object.create(null);
|
||||
|
||||
arr[0].toLowerCase().split('').forEach(c => hash[c] = true);
|
||||
|
||||
return !arr[1].toLowerCase().split('').filter(c => !hash[c]).length;
|
||||
}
|
||||
|
||||
mutation(["hello", "hey"]);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: afcc8d540bea9ea2669306b6
|
||||
title: Repeat a String Repeat a String
|
||||
localeTitle: Repetir una cadena Repetir una cadena
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Repetir una determinada cadena <code>str</code> (primer argumento) para <code>num</code> veces (segundo argumento). Devuelve una cadena vacía si <code>num</code> no es un número positivo.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>repeatStringNumTimes("*", 3)</code> debe devolver <code>"***"</code> .'
|
||||
testString: 'assert(repeatStringNumTimes("*", 3) === "***", "<code>repeatStringNumTimes("*", 3)</code> should return <code>"***"</code>.");'
|
||||
- text: ' <code>repeatStringNumTimes("abc", 3)</code> debe devolver <code>"abcabcabc"</code> .'
|
||||
testString: 'assert(repeatStringNumTimes("abc", 3) === "abcabcabc", "<code>repeatStringNumTimes("abc", 3)</code> should return <code>"abcabcabc"</code>.");'
|
||||
- text: ' <code>repeatStringNumTimes("abc", 4)</code> debe devolver <code>"abcabcabcabc"</code> .'
|
||||
testString: 'assert(repeatStringNumTimes("abc", 4) === "abcabcabcabc", "<code>repeatStringNumTimes("abc", 4)</code> should return <code>"abcabcabcabc"</code>.");'
|
||||
- text: ' <code>repeatStringNumTimes("abc", 1)</code> debe devolver <code>"abc"</code> .'
|
||||
testString: 'assert(repeatStringNumTimes("abc", 1) === "abc", "<code>repeatStringNumTimes("abc", 1)</code> should return <code>"abc"</code>.");'
|
||||
- text: ' <code>repeatStringNumTimes("*", 8)</code> debe devolver <code>"********"</code> .'
|
||||
testString: 'assert(repeatStringNumTimes("*", 8) === "********", "<code>repeatStringNumTimes("*", 8)</code> should return <code>"********"</code>.");'
|
||||
- text: ' <code>repeatStringNumTimes("abc", -2)</code> debe devolver <code>""</code> .'
|
||||
testString: 'assert(repeatStringNumTimes("abc", -2) === "", "<code>repeatStringNumTimes("abc", -2)</code> should return <code>""</code>.");'
|
||||
- text: El método <code>repeat()</code> incorporado no debe utilizarse
|
||||
testString: 'assert(!/\.repeat/g.test(code), "The built-in <code>repeat()</code>-method should not be used");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function repeatStringNumTimes(str, num) {
|
||||
// repeat after me
|
||||
return str;
|
||||
}
|
||||
|
||||
repeatStringNumTimes("abc", 3);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function repeatStringNumTimes(str, num) {
|
||||
if (num < 0) return ";
|
||||
return num === 1 ? str : str + repeatStringNumTimes(str, num-1);
|
||||
}
|
||||
|
||||
repeatStringNumTimes("abc", 3);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: a789b3483989747d63b0e427
|
||||
title: Return Largest Numbers in Arrays
|
||||
localeTitle: Devolver los números más grandes en matrices
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Devolver una matriz que consiste en el número más grande de cada sub-matriz proporcionada. Por simplicidad, la matriz provista contendrá exactamente 4 sub-matrices.
|
||||
Recuerde, puede recorrer una matriz con un simple bucle for, y acceder a cada miembro con sintaxis de matriz <code>arr[i]</code> .
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> debe devolver una matriz. '
|
||||
testString: 'assert(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]).constructor === Array, "<code>largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> should return an array.");'
|
||||
- text: ' <code>largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> debe devolver <code>[27, 5, 39, 1001]</code> .
|
||||
testString: 'assert.deepEqual(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]), [27, 5, 39, 1001], "<code>largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> should return <code>[27, 5, 39, 1001]</code>.");'
|
||||
- text: ' <code>largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])</code> debe devolver <code>[9, 35, 97, 1000000]</code> .
|
||||
testString: 'assert.deepEqual(largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]), [9, 35, 97, 1000000], "<code>largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])</code> should return <code>[9, 35, 97, 1000000]</code>.");'
|
||||
- text: ' <code>largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])</code> debe devolver <code>[25, 48, 21, -3]</code> . '
|
||||
testString: 'assert.deepEqual(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]), [25, 48, 21, -3], "<code>largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])</code> should return <code>[25, 48, 21, -3]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function largestOfFour(arr) {
|
||||
// You can do this!
|
||||
return arr;
|
||||
}
|
||||
|
||||
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function largestOfFour(arr) {
|
||||
return arr.map(subArr => Math.max.apply(null, subArr));
|
||||
}
|
||||
|
||||
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: a202eed8fc186c8434cb6d61
|
||||
title: Reverse a String
|
||||
localeTitle: Revertir una cadena
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Invertir la cadena proporcionada.
|
||||
Es posible que deba convertir la cadena en una matriz antes de poder revertirla.
|
||||
Su resultado debe ser una cadena.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>reverseString("hello")</code> debe devolver una cadena.
|
||||
testString: 'assert(typeof reverseString("hello") === "string", "<code>reverseString("hello")</code> should return a string.");'
|
||||
- text: <code>reverseString("hello")</code> debe convertirse en <code>"olleh"</code> .
|
||||
testString: 'assert(reverseString("hello") === "olleh", "<code>reverseString("hello")</code> should become <code>"olleh"</code>.");'
|
||||
- text: <code>reverseString("Howdy")</code> debe convertirse en <code>"ydwoH"</code> .
|
||||
testString: 'assert(reverseString("Howdy") === "ydwoH", "<code>reverseString("Howdy")</code> should become <code>"ydwoH"</code>.");'
|
||||
- text: <code>reverseString("Greetings from Earth")</code> debe devolver <code>"htraE morf sgniteerG"</code> .
|
||||
testString: 'assert(reverseString("Greetings from Earth") === "htraE morf sgniteerG", "<code>reverseString("Greetings from Earth")</code> should return <code>"htraE morf sgniteerG"</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function reverseString(str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
reverseString("hello");
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function reverseString(str) {
|
||||
return str.split('').reverse().join('');
|
||||
}
|
||||
|
||||
reverseString("hello");
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,92 @@
|
||||
---
|
||||
id: 579e2a2c335b9d72dd32e05c
|
||||
title: Slice and Splice
|
||||
localeTitle: Rebanada y empalme
|
||||
isRequired: true
|
||||
isBeta: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Te dan dos matrices y un índice.
|
||||
Utilice la matriz métodos <code>slice</code> y <code>splice</code> para copiar cada elemento de la primera matriz en la segunda matriz, en orden.
|
||||
Comenzar a insertar elementos en el índice <code>n</code> de la segunda matriz.
|
||||
Devuelve la matriz resultante. Las matrices de entrada deben permanecer iguales después de que se ejecute la función.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>frankenSplice([1, 2, 3], [4, 5], 1)</code> debe devolver <code>[4, 1, 2, 3, 5]</code> .'
|
||||
testString: 'assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5], "<code>frankenSplice([1, 2, 3], [4, 5], 1)</code> should return <code>[4, 1, 2, 3, 5]</code>.");'
|
||||
- text: ' <code>frankenSplice([1, 2], ["a", "b"], 1)</code> debe devolver <code>["a", 1, 2, "b"]</code> .'
|
||||
testString: 'assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ["a", 1, 2, "b"], "<code>frankenSplice([1, 2], ["a", "b"], 1)</code> should return <code>["a", 1, 2, "b"]</code>.");'
|
||||
- text: ' <code>frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)</code> debe devolver <code>["head", "shoulders", "claw", "tentacle", "knees", "toes"]</code> . '
|
||||
testString: 'assert.deepEqual(frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2), ["head", "shoulders", "claw", "tentacle", "knees", "toes"], "<code>frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)</code> should return <code>["head", "shoulders", "claw", "tentacle", "knees", "toes"]</code>.");'
|
||||
- text: Todos los elementos de la primera matriz se deben agregar a la segunda matriz en su orden original.
|
||||
testString: 'assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4], "All elements from the first array should be added to the second array in their original order.");'
|
||||
- text: La primera matriz debe permanecer igual después de que se ejecute la función.
|
||||
testString: 'assert(testArr1[0] === 1 && testArr1[1] === 2, "The first array should remain the same after the function runs.");'
|
||||
- text: La segunda matriz debe permanecer igual después de que se ejecute la función.
|
||||
testString: 'assert(testArr2[0] === "a" && testArr2[1] === "b", "The second array should remain the same after the function runs.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
// It's alive. It's alive!
|
||||
return arr2;
|
||||
}
|
||||
|
||||
frankenSplice([1, 2, 3], [4, 5, 6], 1);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
// It's alive. It's alive!
|
||||
let result = arr2.slice();
|
||||
for (let i = 0; i < arr1.length; i++) {
|
||||
result.splice(n+i, 0, arr1[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
frankenSplice([1, 2, 3], [4, 5], 1);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
id: ab6137d4e35944e21037b769
|
||||
title: Title Case a Sentence
|
||||
localeTitle: Título Caso una oración
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Devuelva la cadena provista con la primera letra de cada palabra en mayúscula. Asegúrese de que el resto de la palabra esté en minúscula.
|
||||
A los efectos de este ejercicio, también debe poner mayúsculas en las palabras de conexión como "el" y "de".
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>titleCase("I'm a little tea pot")</code> debería devolver una cadena.'
|
||||
testString: 'assert(typeof titleCase("I"m a little tea pot") === "string", "<code>titleCase("I'm a little tea pot")</code> should return a string.");'
|
||||
- text: ' <code>titleCase("I'm a little tea pot")</code> debería devolver <code>I'm A Little Tea Pot</code> '.
|
||||
testString: 'assert(titleCase("I"m a little tea pot") === "I"m A Little Tea Pot", "<code>titleCase("I'm a little tea pot")</code> should return <code>I'm A Little Tea Pot</code>.");'
|
||||
- text: <code>titleCase("sHoRt AnD sToUt")</code> debe devolver <code>Short And Stout</code> .
|
||||
testString: 'assert(titleCase("sHoRt AnD sToUt") === "Short And Stout", "<code>titleCase("sHoRt AnD sToUt")</code> should return <code>Short And Stout</code>.");'
|
||||
- text: <code>titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")</code> debería regresar. <code>Here Is My Handle Here Is My Spout</code> .
|
||||
testString: 'assert(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") === "Here Is My Handle Here Is My Spout", "<code>titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")</code> should return <code>Here Is My Handle Here Is My Spout</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function titleCase(str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
titleCase("I'm a little tea pot");
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function titleCase(str) {
|
||||
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()).join(' ');
|
||||
}
|
||||
|
||||
titleCase("I'm a little tea pot");
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: ac6993d51946422351508a41
|
||||
title: Truncate a String
|
||||
localeTitle: Truncar una cadena
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Truncar una cadena (primer argumento) si es más larga que la longitud de cadena máxima dada (segundo argumento). Devuelve la cadena truncada con un <code>...</code> final.
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>truncateString("A-tisket a-tasket A green and yellow basket", 8)</code> debe devolver "A-tisket ...".'
|
||||
testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", 8) === "A-tisket...", "<code>truncateString("A-tisket a-tasket A green and yellow basket", 8)</code> should return "A-tisket...".");'
|
||||
- text: ' <code>truncateString("Peter Piper picked a peck of pickled peppers", 11)</code> debería devolver "Peter Piper ...".
|
||||
testString: 'assert(truncateString("Peter Piper picked a peck of pickled peppers", 11) === "Peter Piper...", "<code>truncateString("Peter Piper picked a peck of pickled peppers", 11)</code> should return "Peter Piper...".");'
|
||||
- text: ' <code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)</code> debe devolver "A-tisket a-tasket Una canasta verde y amarilla".'
|
||||
testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) === "A-tisket a-tasket A green and yellow basket", "<code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)</code> should return "A-tisket a-tasket A green and yellow basket".");'
|
||||
- text: ' <code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)</code> debe devolver "A-tisket a-tasket Una canasta verde y amarilla" .
|
||||
testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) === "A-tisket a-tasket A green and yellow basket", "<code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)</code> should return "A-tisket a-tasket A green and yellow basket".");'
|
||||
- text: ' <code>truncateString("A-", 1)</code> debe devolver "A ...".'
|
||||
testString: 'assert(truncateString("A-", 1) === "A...", "<code>truncateString("A-", 1)</code> should return "A...".");'
|
||||
- text: ' <code>truncateString("Absolutely Longer", 2)</code> debe devolver "Ab ...".'
|
||||
testString: 'assert(truncateString("Absolutely Longer", 2) === "Ab...", "<code>truncateString("Absolutely Longer", 2)</code> should return "Ab...".");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function truncateString(str, num) {
|
||||
// Clear out that junk in your trunk
|
||||
return str;
|
||||
}
|
||||
|
||||
truncateString("A-tisket a-tasket A green and yellow basket", 8);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function truncateString(str, num) {
|
||||
if (num >= str.length) {
|
||||
return str;
|
||||
}
|
||||
|
||||
return str.slice(0, num) + '...';
|
||||
}
|
||||
|
||||
truncateString("A-tisket a-tasket A green and yellow basket", 8);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,105 @@
|
||||
---
|
||||
id: a24c1a4622e3c05097f71d67
|
||||
title: Where do I Belong
|
||||
localeTitle: Dónde pertenezco
|
||||
isRequired: true
|
||||
challengeType: 5
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Devuelva el índice más bajo en el que se debe insertar un valor (segundo argumento) en una matriz (primer argumento) una vez que se haya ordenado. El valor devuelto debe ser un número.
|
||||
Por ejemplo, <code>getIndexToIns([1,2,3,4], 1.5)</code> debe devolver <code>1</code> porque es mayor que <code>1</code> (índice 0), pero menor que <code>2</code> (índice 1).
|
||||
Del mismo modo, <code>getIndexToIns([20,3,5], 19)</code> debe devolver <code>2</code> porque una vez que se ha ordenado la matriz se verá como <code>[3,5,20]</code> y <code>19</code> es menor que <code>20</code> (índice 2) y mayor que <code>5</code> (índice 1).
|
||||
Recuerda usar <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> si te atascas. Escribe tu propio código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> debe devolver <code>3</code> '
|
||||
testString: 'assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3, "<code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> should return <code>3</code>.");'
|
||||
- text: ' <code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> debe devolver un número'.
|
||||
testString: 'assert(typeof(getIndexToIns([10, 20, 30, 40, 50], 35)) === "number", "<code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> should return a number.");'
|
||||
- text: ' <code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> debe devolver <code>2</code> '
|
||||
testString: 'assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2, "<code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> should return <code>2</code>.");'
|
||||
- text: ' <code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> debe devolver un número'.
|
||||
testString: 'assert(typeof(getIndexToIns([10, 20, 30, 40, 50], 30)) === "number", "<code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> should return a number.");'
|
||||
- text: ' <code>getIndexToIns([40, 60], 50)</code> debe devolver <code>1</code> '
|
||||
testString: 'assert(getIndexToIns([40, 60], 50) === 1, "<code>getIndexToIns([40, 60], 50)</code> should return <code>1</code>.");'
|
||||
- text: ' <code>getIndexToIns([40, 60], 50)</code> debe devolver un número.'
|
||||
testString: 'assert(typeof(getIndexToIns([40, 60], 50)) === "number", "<code>getIndexToIns([40, 60], 50)</code> should return a number.");'
|
||||
- text: ' <code>getIndexToIns([3, 10, 5], 3)</code> debe devolver <code>0</code> '
|
||||
testString: 'assert(getIndexToIns([3, 10, 5], 3) === 0, "<code>getIndexToIns([3, 10, 5], 3)</code> should return <code>0</code>.");'
|
||||
- text: ' <code>getIndexToIns([3, 10, 5], 3)</code> debe devolver un número'.
|
||||
testString: 'assert(typeof(getIndexToIns([3, 10, 5], 3)) === "number", "<code>getIndexToIns([3, 10, 5], 3)</code> should return a number.");'
|
||||
- text: ' <code>getIndexToIns([5, 3, 20, 3], 5)</code> debe devolver <code>2</code> '
|
||||
testString: 'assert(getIndexToIns([5, 3, 20, 3], 5) === 2, "<code>getIndexToIns([5, 3, 20, 3], 5)</code> should return <code>2</code>.");'
|
||||
- text: ' <code>getIndexToIns([5, 3, 20, 3], 5)</code> debe devolver un número'.
|
||||
testString: 'assert(typeof(getIndexToIns([5, 3, 20, 3], 5)) === "number", "<code>getIndexToIns([5, 3, 20, 3], 5)</code> should return a number.");'
|
||||
- text: ' <code>getIndexToIns([2, 20, 10], 19)</code> debe devolver <code>2</code> '
|
||||
testString: 'assert(getIndexToIns([2, 20, 10], 19) === 2, "<code>getIndexToIns([2, 20, 10], 19)</code> should return <code>2</code>.");'
|
||||
- text: ' <code>getIndexToIns([2, 20, 10], 19)</code> debe devolver un número'.
|
||||
testString: 'assert(typeof(getIndexToIns([2, 20, 10], 19)) === "number", "<code>getIndexToIns([2, 20, 10], 19)</code> should return a number.");'
|
||||
- text: ' <code>getIndexToIns([2, 5, 10], 15)</code> debe devolver <code>3</code> '
|
||||
testString: 'assert(getIndexToIns([2, 5, 10], 15) === 3, "<code>getIndexToIns([2, 5, 10], 15)</code> should return <code>3</code>.");'
|
||||
- text: ' <code>getIndexToIns([2, 5, 10], 15)</code> debe devolver un número'.
|
||||
testString: 'assert(typeof(getIndexToIns([2, 5, 10], 15)) === "number", "<code>getIndexToIns([2, 5, 10], 15)</code> should return a number.");'
|
||||
- text: ' <code>getIndexToIns([], 1)</code> debe devolver <code>0</code> '
|
||||
testString: 'assert(getIndexToIns([], 1) === 0, "<code>getIndexToIns([], 1)</code> should return <code>0</code>.");'
|
||||
- text: ' <code>getIndexToIns([], 1)</code> debe devolver un número.'
|
||||
testString: 'assert(typeof(getIndexToIns([], 1)) === "number", "<code>getIndexToIns([], 1)</code> should return a number.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function getIndexToIns(arr, num) {
|
||||
// Find my place in this sorted array.
|
||||
return num;
|
||||
}
|
||||
|
||||
getIndexToIns([40, 60], 50);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function getIndexToIns(arr, num) {
|
||||
arr = arr.sort((a, b) => a - b);
|
||||
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
if (arr[i] >= num) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return arr.length;
|
||||
}
|
||||
|
||||
getIndexToIns([40, 60], 50);
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,81 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1d
|
||||
title: ' Iterate Through the Keys of an Object with a for...in Statement'
|
||||
localeTitle: 'Iterar a través de las claves de un objeto con una for ... in Statement'
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
A veces es posible que deba recorrer todas las claves dentro de un objeto. Esto requiere una sintaxis específica en JavaScript llamada <dfn>for ... in</dfn> statement. Para el objeto de nuestros <code>users</code> , esto podría verse como:
|
||||
<blockquote>for (let user in users) {<br> console.log(user);<br>};<br><br>// logs:<br>Alan<br>Jeff<br>Sarah<br>Ryan</blockquote>
|
||||
En esta declaración, definimos una variable de <code>user</code> y, como puede ver, esta variable se restableció durante cada iteración de cada una de las claves del objeto a medida que la declaración se desplazaba a través del objeto, lo que daba como resultado que el nombre de cada usuario se imprimiera en la consola.
|
||||
<strong>NOTA:</strong> <br> Los objetos no mantienen un orden para las claves almacenadas como lo hacen las matrices; por lo tanto, una posición de las teclas en un objeto, o el orden relativo en el que aparece, es irrelevante cuando se hace referencia o se accede a esa tecla.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>countOnline</code> ; use una instrucción <dfn>for ... in</dfn> dentro de esta función para recorrer los usuarios en el objeto de los <code>users</code> y devolver el número de usuarios cuya propiedad en <code>online</code> está establecida en <code>true</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: El objeto <code>users</code> contiene a los usuarios <code>Jeff</code> y <code>Ryan</code> con <code>online</code> conjunto en <code>online</code> a <code>true</code> y los usuarios <code>Alan</code> y <code>Sarah</code> con <code>online</code> conjunto en <code>online</code> a <code>false</code>
|
||||
testString: 'assert(users.Alan.online === false && users.Jeff.online === true && users.Sarah.online === false && users.Ryan.online === true, "The <code>users</code> object contains users <code>Jeff</code> and <code>Ryan</code> with <code>online</code> set to <code>true</code> and users <code>Alan</code> and <code>Sarah</code> with <code>online</code> set to <code>false</code>");'
|
||||
- text: La función <code>countOnline</code> devuelve el número de usuarios con la propiedad en <code>online</code> establecida en <code>true</code>
|
||||
testString: 'assert((function() { users.Harry = {online: true}; users.Sam = {online: true}; users.Carl = {online: true}; return countOnline(users) })() === 5, "The function <code>countOnline</code> returns the number of users with the <code>online</code> property set to <code>true</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: false
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function countOnline(obj) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
}
|
||||
|
||||
console.log(countOnline(users));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 5a661e0f1068aca922b3ef17
|
||||
title: Access an Array's Contents Using Bracket Notation
|
||||
localeTitle: Acceder a los contenidos de una matriz usando notación de corchete
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
La característica fundamental de cualquier estructura de datos es, por supuesto, la capacidad no solo de almacenar datos, sino también de poder recuperar esos datos en el comando. Entonces, ahora que hemos aprendido cómo crear una matriz, comencemos a pensar cómo podemos acceder a la información de esa matriz.
|
||||
Cuando definimos una matriz simple como se ve a continuación, hay 3 elementos en ella:
|
||||
<blockquote>let ourArray = ["a", "b", "c"];</blockquote>
|
||||
En una matriz, cada elemento de la matriz tiene un <dfn>índice</dfn> . Este índice se duplica como la posición de ese elemento en la matriz y cómo se hace referencia a él. Sin embargo, es importante tener en cuenta que las matrices de JavaScript tienen <dfn>un índice de cero</dfn> , lo que significa que el primer elemento de una matriz está en realidad en la posición <em><strong>cero</strong></em> , no en el primero.
|
||||
Para recuperar un elemento de una matriz, podemos encerrar un índice entre paréntesis y agregarlo al final de una matriz, o más comúnmente, a una variable que hace referencia a un objeto de matriz. Esto se conoce como <dfn>notación de corchete</dfn> .
|
||||
Por ejemplo, si queremos recuperar la <code>"a"</code> de <code>ourArray</code> y asignarla a una variable, podemos hacerlo con el siguiente código:
|
||||
<blockquote>let ourVariable = ourArray[0];<br>// ourVariable equals "a"</blockquote>
|
||||
Además de acceder al valor asociado a un índice, también puede <em>establecer</em> un índice en un valor usando la misma notación:
|
||||
<blockquote>ourArray[1] = "not b anymore";<br>// ourArray now equals ["a", "not b anymore", "c"];</blockquote>
|
||||
Usando la notación de corchetes, ahora hemos restablecido el elemento en el índice 1 de <code>"b"</code> , a <code>"not b anymore"</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Para completar este desafío, establezca la segunda posición (índice <code>1</code> ) de <code>myArray</code> en cualquier cosa que desee, además de <code>"b"</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>myArray[0]</code> es igual a <code>"a"</code> '
|
||||
testString: 'assert.strictEqual(myArray[0], "a", "<code>myArray[0]</code> is equal to <code>"a"</code>");'
|
||||
- text: ' <code>myArray[1]</code> ya no está configurado en <code>"b"</code> '
|
||||
testString: 'assert.notStrictEqual(myArray[1], "b", "<code>myArray[1]</code> is no longer set to <code>"b"</code>");'
|
||||
- text: ' <code>myArray[2]</code> es igual a <code>"c"</code> '
|
||||
testString: 'assert.strictEqual(myArray[2], "c", "<code>myArray[2]</code> is equal to <code>"c"</code>");'
|
||||
- text: ' <code>myArray[3]</code> es igual a <code>"d"</code> '
|
||||
testString: 'assert.strictEqual(myArray[3], "d", "<code>myArray[3]</code> is equal to <code>"d"</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let myArray = ["a", "b", "c", "d"];
|
||||
// change code below this line
|
||||
|
||||
//change code above this line
|
||||
console.log(myArray);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1a
|
||||
title: Access Property Names with Bracket Notation
|
||||
localeTitle: Acceso a nombres de propiedades con notación de corchete
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En el primer desafío de objetos mencionamos el uso de la notación de corchetes como una forma de acceder a los valores de las propiedades mediante la evaluación de una variable. Por ejemplo, imagine que nuestro objeto de <code>foods</code> se está utilizando en un programa para una caja registradora de un supermercado. Tenemos alguna función que configura los <code>foods</code> <code>selectedFood</code> y queremos verificar el objeto de nuestros <code>foods</code> para detectar la presencia de ese alimento. Esto podría parecer:
|
||||
<blockquote>let selectedFood = getCurrentFood(scannedItem);<br>let inventory = foods[selectedFood];</blockquote>
|
||||
Este código evaluará el valor almacenado en la variable <code>selectedFood</code> y devolverá el valor de esa clave en el objeto de <code>foods</code> , o <code>undefined</code> si no está presente. La notación de corchetes es muy útil porque a veces las propiedades de los objetos no se conocen antes del tiempo de ejecución o necesitamos acceder a ellos de una manera más dinámica.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>checkInventory</code> , que recibe un elemento escaneado como un argumento. Devuelve el valor actual de la clave <code>scannedItem</code> en el objeto de <code>foods</code> . Puede suponer que solo se proporcionarán claves válidas como argumento para <code>checkInventory</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>checkInventory</code> es una función
|
||||
testString: 'assert.strictEqual(typeof checkInventory, "function", "<code>checkInventory</code> is a function");'
|
||||
- text: 'El objeto de <code>foods</code> debe tener solo los siguientes pares clave-valor: <code>apples: 25</code> , <code>oranges: 32</code> , <code>plums: 28</code> , <code>bananas: 13</code> , <code>grapes: 35</code> , <code>strawberries: 27</code> '
|
||||
testString: 'assert.deepEqual(foods, {apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27}, "The <code>foods</code> object should have only the following key-value pairs: <code>apples: 25</code>, <code>oranges: 32</code>, <code>plums: 28</code>, <code>bananas: 13</code>, <code>grapes: 35</code>, <code>strawberries: 27</code>");'
|
||||
- text: <code>checkInventory("apples")</code> debe devolver <code>25</code>
|
||||
testString: 'assert.strictEqual(checkInventory("apples"), 25, "<code>checkInventory("apples")</code> should return <code>25</code>");'
|
||||
- text: <code>checkInventory("bananas")</code> debe devolver <code>13</code>
|
||||
testString: 'assert.strictEqual(checkInventory("bananas"), 13, "<code>checkInventory("bananas")</code> should return <code>13</code>");'
|
||||
- text: <code>checkInventory("strawberries")</code> debe devolver <code>27</code>
|
||||
testString: 'assert.strictEqual(checkInventory("strawberries"), 27, "<code>checkInventory("strawberries")</code> should return <code>27</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
// do not change code above this line
|
||||
|
||||
function checkInventory(scannedItem) {
|
||||
// change code below this line
|
||||
|
||||
}
|
||||
|
||||
// change code below this line to test different cases:
|
||||
console.log(checkInventory("apples"));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0e
|
||||
title: Add Items to an Array with push() and unshift()
|
||||
localeTitle: Agregar elementos a una matriz con push () y unshift ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
La longitud de una matriz, como los tipos de datos que puede contener, no es fija. Las matrices se pueden definir con una longitud de cualquier número de elementos, y los elementos se pueden agregar o eliminar con el tiempo; en otras palabras, los arreglos son <dfn>mutables</dfn> . En este desafío, veremos dos métodos con los cuales podemos modificar mediante programación una matriz: <code>Array.push()</code> y <code>Array.unshift()</code> .
|
||||
Ambos métodos toman uno o más elementos como parámetros y agregan esos elementos a la matriz en la que se está utilizando el método; el método <code>push()</code> agrega elementos al final de una matriz, y <code>unshift()</code> agrega elementos al principio. Considera lo siguiente:
|
||||
<blockquote>let twentyThree = 'XXIII';<br>let romanNumerals = ['XXI', 'XXII'];<br><br>romanNumerals.unshift('XIX', 'XX');<br>// now equals ['XIX', 'XX', 'XXI', 'XXII']<br><br>romanNumerals.push(twentyThree);<br>// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']
|
||||
Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>mixedNumbers</code> , a la que le estamos pasando una matriz como argumento. Modifique la función utilizando <code>push()</code> y <code>unshift()</code> para agregar <code>'I', 2, 'three'</code> al principio de la matriz y <code>7, 'VIII', 9</code> al final para que la matriz devuelta contenga representaciones de los números 1-9 en orden.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>mixedNumbers(["IV", 5, "six"])</code> ahora debe devolver <code>["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]</code> '
|
||||
testString: 'assert.deepEqual(mixedNumbers(["IV", 5, "six"]), ["I", 2, "three", "IV", 5, "six", 7, "VIII", 9], "<code>mixedNumbers(["IV", 5, "six"])</code> should now return <code>["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]</code>");'
|
||||
- text: La función <code>mixedNumbers</code> debe utilizar el método <code>push()</code>
|
||||
testString: 'assert.notStrictEqual(mixedNumbers.toString().search(/\.push\(/), -1, "The <code>mixedNumbers</code> function should utilize the <code>push()</code> method");'
|
||||
- text: La función <code>mixedNumbers</code> debe utilizar el método <code>unshift()</code>
|
||||
testString: 'assert.notStrictEqual(mixedNumbers.toString().search(/\.unshift\(/), -1, "The <code>mixedNumbers</code> function should utilize the <code>unshift()</code> method");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function mixedNumbers(arr) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
return arr;
|
||||
}
|
||||
|
||||
// do not change code below this line
|
||||
console.log(mixedNumbers(['IV', 5, 'six']));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 587d78b3367417b2b2512b11
|
||||
title: Add Items Using splice()
|
||||
localeTitle: Agregar artículos usando splice ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Recuerda que en el último desafío mencionamos que <code>splice()</code> puede tomar hasta tres parámetros? Bueno, podemos ir un paso más allá con <code>splice()</code> ; además de eliminar elementos, podemos usar ese tercer parámetro, que representa uno o más elementos, para <em>agregarlos</em> también. Esto puede ser increíblemente útil para cambiar rápidamente un elemento, o un conjunto de elementos, por otro. Por ejemplo, supongamos que está almacenando una combinación de colores para un conjunto de elementos DOM en una matriz, y desea cambiar dinámicamente un color en función de alguna acción:
|
||||
<blockquote>function colorChange(arr, index, newColor) {<br> arr.splice(index, 1, newColor);<br> return arr;<br>}<br><br>let colorScheme = ['#878787', '#a08794', '#bb7e8c', '#c9b6be', '#d1becf'];<br><br>colorScheme = colorChange(colorScheme, 2, '#332327');<br>// we have removed '#bb7e8c' and added '#332327' in its place<br>// colorScheme now equals ['#878787', '#a08794', '#332327', '#c9b6be', '#d1becf']</blockquote>
|
||||
Esta función toma una matriz de valores hexadecimales, un índice para eliminar un elemento y el nuevo color para reemplazar el elemento eliminado. El valor de retorno es una matriz que contiene un esquema de color recién modificado. Si bien este ejemplo está un poco simplificado, podemos ver el valor que puede tener el uso de <code>splice()</code> en su potencial máximo.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>htmlColorNames</code> , que toma una matriz de colores HTML como argumento. Modifique la función utilizando <code>splice()</code> para eliminar los dos primeros elementos de la matriz y agregue <code>'DarkSalmon'</code> y <code>'BlanchedAlmond'</code> en sus respectivos lugares.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>htmlColorNames</code> debería devolver <code>["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]</code> '
|
||||
testString: 'assert.deepEqual(htmlColorNames(["DarkGoldenRod", "WhiteSmoke", "LavenderBlush", "PaleTurqoise", "FireBrick"]), ["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"], "<code>htmlColorNames</code> should return <code>["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]</code>");'
|
||||
- text: La función <code>htmlColorNames</code> debe utilizar el método <code>splice()</code>
|
||||
testString: 'assert(/.splice/.test(code), "The <code>htmlColorNames</code> function should utilize the <code>splice()</code> method");'
|
||||
- text: No debes usar <code>shift()</code> o <code>unshift()</code> .
|
||||
testString: 'assert(!/shift|unshift/.test(code), "You should not use <code>shift()</code> or <code>unshift()</code>.");'
|
||||
- text: No debe utilizar la notación de soporte de matriz.
|
||||
testString: 'assert(!/\[\d\]\s*=/.test(code), "You should not use array bracket notation.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function htmlColorNames(arr) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
return arr;
|
||||
}
|
||||
|
||||
// do not change code below this line
|
||||
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick']));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b18
|
||||
title: Add Key-Value Pairs to JavaScript Objects
|
||||
localeTitle: Agregue pares de valor-clave a los objetos de JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En su forma más básica, los objetos son solo colecciones de <dfn>pares clave-valor</dfn> , o, en otras palabras, fragmentos de datos asignados a identificadores únicos que llamamos <dfn>propiedades</dfn> o <dfn>claves</dfn> . Veamos un ejemplo muy simple:
|
||||
<blockquote>let FCC_User = {<br> username: 'awesome_coder',<br> followers: 572,<br> points: 1741,<br> completedProjects: 15<br>};</blockquote>
|
||||
El código anterior define un objeto llamado <code>FCC_User</code> que tiene cuatro <dfn>propiedades</dfn> , cada una de las cuales se <code>FCC_User</code> a un valor específico. Si quisiéramos saber el número de <code>followers</code> tiene <code>FCC_User</code> , podemos acceder a esa propiedad escribiendo:
|
||||
<blockquote>let userData = FCC_User.followers;<br>// userData equals 572</blockquote>
|
||||
Esto se llama <dfn>notación de puntos</dfn> . Alternativamente, también podemos acceder a la propiedad entre paréntesis, así:
|
||||
<blockquote>let userData = FCC_User['followers']<br>// userData equals 572</blockquote>
|
||||
Observe que con la <dfn>notación de corchetes</dfn> , incluimos a los <code>followers</code> entre comillas. Esto se debe a que los corchetes realmente nos permiten pasar una variable para que sea evaluada como un nombre de propiedad (sugerencia: ten esto en cuenta para más adelante). Si hubiéramos pasado a los <code>followers</code> sin las comillas, el motor de JavaScript habría intentado evaluarla como una variable, y un <code>ReferenceError: followers is not defined</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Usando la misma sintaxis, también podemos <em><strong>agregar nuevos</strong></em> pares clave-valor a los objetos. Hemos creado un objeto de <code>foods</code> con tres entradas. Agregue tres entradas más: <code>bananas</code> con un valor de <code>13</code> , <code>grapes</code> con un valor de <code>35</code> y <code>strawberries</code> con un valor de <code>27</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>foods</code> son un objeto
|
||||
testString: 'assert(typeof foods === "object", "<code>foods</code> is an object");'
|
||||
- text: El objeto <code>foods</code> tiene una clave <code>"bananas"</code> con un valor de <code>13</code>
|
||||
testString: 'assert(foods.bananas === 13, "The <code>foods</code> object has a key <code>"bananas"</code> with a value of <code>13</code>");'
|
||||
- text: El objeto <code>foods</code> tiene una clave <code>"grapes"</code> con un valor de <code>35</code>
|
||||
testString: 'assert(foods.grapes === 35, "The <code>foods</code> object has a key <code>"grapes"</code> with a value of <code>35</code>");'
|
||||
- text: El objeto de <code>foods</code> tiene una clave <code>"strawberries"</code> con un valor de <code>27</code>
|
||||
testString: 'assert(foods.strawberries === 27, "The <code>foods</code> object has a key <code>"strawberries"</code> with a value of <code>27</code>");'
|
||||
- text: Los pares clave-valor deben configurarse usando notación de punto o corchete
|
||||
testString: 'assert(code.search(/bananas:/) === -1 && code.search(/grapes:/) === -1 && code.search(/strawberries:/) === -1, "The key-value pairs should be set using dot or bracket notation");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28
|
||||
};
|
||||
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
|
||||
console.log(foods);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b14
|
||||
title: Check For The Presence of an Element With indexOf()
|
||||
localeTitle: Comprobar la presencia de un elemento con indexOf ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Dado que las matrices se pueden cambiar, o <em>mutar</em> , en cualquier momento, no hay ninguna garantía sobre dónde estará una determinada pieza de datos en una matriz determinada, o si ese elemento aún existe. Afortunadamente, JavaScript nos proporciona otro método <code>indexOf()</code> , <code>indexOf()</code> , que nos permite verificar rápida y fácilmente la presencia de un elemento en una matriz. <code>indexOf()</code> toma un elemento como parámetro y, cuando se le llama, devuelve la posición o el índice de ese elemento, o <code>-1</code> si el elemento no existe en la matriz.
|
||||
Por ejemplo:
|
||||
<blockquote>let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];<br><br>fruits.indexOf('dates') // returns -1<br>fruits.indexOf('oranges') // returns 2<br>fruits.indexOf('pears') // returns 1, the first index at which the element exists</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<code>indexOf()</code> puede ser increíblemente útil para verificar rápidamente la presencia de un elemento en una matriz. Hemos definido una función, <code>quickCheck</code> , que toma una matriz y un elemento como argumentos. Modifique la función utilizando <code>indexOf()</code> para que devuelva <code>true</code> si el elemento pasado existe en la matriz, y <code>false</code> si no lo hace.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> debe devolver <code>false</code> '
|
||||
testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "mushrooms"), false, "<code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> should return <code>false</code>");'
|
||||
- text: ' <code>quickCheck(["squash", "onions", "shallots"], "onions")</code> debe devolver <code>true</code> "
|
||||
testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "onions"), true, "<code>quickCheck(["squash", "onions", "shallots"], "onions")</code> should return <code>true</code>");'
|
||||
- text: ' <code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> debe devolver <code>true</code> '
|
||||
testString: 'assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, "<code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> should return <code>true</code>");'
|
||||
- text: ' <code>quickCheck([true, false, false], undefined)</code> debe devolver <code>false</code> '
|
||||
testString: 'assert.strictEqual(quickCheck([true, false, false], undefined), false, "<code>quickCheck([true, false, false], undefined)</code> should return <code>false</code>");'
|
||||
- text: La función <code>quickCheck</code> debe utilizar el método <code>indexOf()</code>
|
||||
testString: 'assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1, "The <code>quickCheck</code> function should utilize the <code>indexOf()</code> method");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function quickCheck(arr, elem) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
}
|
||||
|
||||
// change code here to test different cases:
|
||||
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,81 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1c
|
||||
title: Check if an Object has a Property
|
||||
localeTitle: Compruebe si un objeto tiene una propiedad
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Ahora podemos agregar, modificar y eliminar claves de objetos. Pero, ¿y si solo quisiéramos saber si un objeto tiene una propiedad específica? JavaScript nos proporciona dos formas diferentes de hacer esto. Uno usa el método <code>hasOwnProperty()</code> y el otro usa la palabra clave <code>in</code> . Si tenemos un objeto <code>users</code> con una propiedad de <code>Alan</code> , podríamos verificar su presencia de una de las siguientes maneras:
|
||||
<blockquote>users.hasOwnProperty('Alan');<br>'Alan' in users;<br>// both return true</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos creado un objeto, <code>users</code> , con algunos usuarios en él y una función <code>isEveryoneHere</code> , a la que pasamos el objeto de los <code>users</code> como un argumento. Termine de escribir esta función de modo que devuelva <code>true</code> solo si el objeto de los <code>users</code> contiene los cuatro nombres, <code>Alan</code> , <code>Jeff</code> , <code>Sarah</code> y <code>Ryan</code> , como claves, y en caso contrario, <code>false</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'El objeto de los <code>users</code> solo contiene las claves <code>Alan</code> , <code>Jeff</code> , <code>Sarah</code> y <code>Ryan</code> '
|
||||
testString: 'assert("Alan" in users && "Jeff" in users && "Sarah" in users && "Ryan" in users && Object.keys(users).length === 4, "The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>");'
|
||||
- text: 'La función <code>isEveryoneHere</code> devuelve <code>true</code> si <code>Alan</code> , <code>Jeff</code> , <code>Sarah</code> y <code>Ryan</code> son propiedades del objeto de los <code>users</code> '
|
||||
testString: 'assert(isEveryoneHere(users) === true, "The function <code>isEveryoneHere</code> returns <code>true</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are properties on the <code>users</code> object");'
|
||||
- text: 'La función <code>isEveryoneHere</code> devuelve <code>false</code> si <code>Alan</code> , <code>Jeff</code> , <code>Sarah</code> y <code>Ryan</code> no son propiedades del objeto de los <code>users</code> '
|
||||
testString: 'assert((function() { delete users.Alan; delete users.Jeff; delete users.Sarah; delete users.Ryan; return isEveryoneHere(users) })() === false, "The function <code>isEveryoneHere</code> returns <code>false</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are not properties on the <code>users</code> object");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: true
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: true
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function isEveryoneHere(obj) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
}
|
||||
|
||||
console.log(isEveryoneHere(users));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,62 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b17
|
||||
title: Combine Arrays with the Spread Operator
|
||||
localeTitle: Combina matrices con el operador de propagación
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Otra gran ventaja del operador de <dfn>difusión</dfn> , es la capacidad de combinar arreglos, o de insertar todos los elementos de un arreglo en otro, en cualquier índice. Con sintaxis más tradicionales, podemos concatenar matrices, pero esto solo nos permite combinar matrices al final de una y al comienzo de otra. La sintaxis de propagación hace que la siguiente operación sea extremadamente simple:
|
||||
<blockquote>let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];<br><br>let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];<br>// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']</blockquote>
|
||||
Usando la sintaxis de propagación, acabamos de lograr una operación que hubiera sido más compleja y más detallada si hubiéramos usado métodos tradicionales.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función <code>spreadOut</code> que devuelve la <code>sentence</code> variable, modifique la función usando el operador de <dfn>propagación</dfn> para que devuelva la matriz <code>['learning', 'to', 'code', 'is', 'fun']</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>spreadOut</code> debería devolver <code>["learning", "to", "code", "is", "fun"]</code> '
|
||||
testString: 'assert.deepEqual(spreadOut(), ["learning", "to", "code", "is", "fun"], "<code>spreadOut</code> should return <code>["learning", "to", "code", "is", "fun"]</code>");'
|
||||
- text: La función <code>spreadOut</code> debe utilizar la sintaxis de difusión
|
||||
testString: 'assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1, "The <code>spreadOut</code> function should utilize spread syntax");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function spreadOut() {
|
||||
let fragment = ['to', 'code'];
|
||||
let sentence; // change this line
|
||||
return sentence;
|
||||
}
|
||||
|
||||
// do not change code below this line
|
||||
console.log(spreadOut());
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b13
|
||||
title: Copy an Array with the Spread Operator
|
||||
localeTitle: Copiar una matriz con el operador de propagación
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Mientras <code>slice()</code> nos permite ser selectivos sobre qué elementos de una matriz copiar, entre otras muchas tareas útiles, el nuevo <dfn>operador de difusión de</dfn> ES6 nos permite copiar fácilmente <em>todos</em> los elementos de una matriz, en orden, con una sintaxis simple y altamente legible . La sintaxis de propagación simplemente se ve así: <code>...</code>
|
||||
En la práctica, podemos usar el operador de propagación para copiar una matriz de la siguiente manera:
|
||||
<blockquote>let thisArray = [true, true, undefined, false, null];<br>let thatArray = [...thisArray];<br>// thatArray equals [true, true, undefined, false, null]<br>// thisArray remains unchanged, and is identical to thatArray</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>copyMachine</code> que toma <code>arr</code> (una matriz) y <code>num</code> (un número) como argumentos. Se supone que la función devuelve una nueva matriz formada por <code>num</code> copias de <code>arr</code> . Hemos hecho la mayor parte del trabajo por usted, pero todavía no funciona del todo bien. Modifique la función utilizando la sintaxis de dispersión para que funcione correctamente (sugerencia: ¡otro método que ya hemos cubierto podría ser útil aquí!).
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>copyMachine([true, false, true], 2)</code> debe devolver <code>[[true, false, true], [true, false, true]]</code> '
|
||||
testString: 'assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]], "<code>copyMachine([true, false, true], 2)</code> should return <code>[[true, false, true], [true, false, true]]</code>");'
|
||||
- text: ' <code>copyMachine([1, 2, 3], 5)</code> debe devolver <code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code> '
|
||||
testString: 'assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]], "<code>copyMachine([1, 2, 3], 5)</code> should return <code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code>");'
|
||||
- text: ' <code>copyMachine([true, true, null], 1)</code> debe devolver <code>[[true, true, null]]</code> '
|
||||
testString: 'assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]], "<code>copyMachine([true, true, null], 1)</code> should return <code>[[true, true, null]]</code>");'
|
||||
- text: ' <code>copyMachine(["it works"], 3)</code> debería devolver <code>[["it works"], ["it works"], ["it works"]]</code> '
|
||||
testString: 'assert.deepEqual(copyMachine(["it works"], 3), [["it works"], ["it works"], ["it works"]], "<code>copyMachine(["it works"], 3)</code> should return <code>[["it works"], ["it works"], ["it works"]]</code>");'
|
||||
- text: La función <code>copyMachine</code> debe utilizar el <code>spread operator</code> con array <code>arr</code>
|
||||
testString: 'assert.notStrictEqual(copyMachine.toString().indexOf(".concat(_toConsumableArray(arr))"), -1, "The <code>copyMachine</code> function should utilize the <code>spread operator</code> with array <code>arr</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function copyMachine(arr, num) {
|
||||
let newArr = [];
|
||||
while (num >= 1) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
num--;
|
||||
}
|
||||
return newArr;
|
||||
}
|
||||
|
||||
// change code here to test different cases:
|
||||
console.log(copyMachine([true, false, true], 2));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,62 @@
|
||||
---
|
||||
id: 587d7b7a367417b2b2512b12
|
||||
title: Copy Array Items Using slice()
|
||||
localeTitle: Copiar elementos de matriz utilizando slice ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El siguiente método que cubriremos es <code>slice()</code> . <code>slice()</code> , en lugar de modificar una matriz, copia o <em>extrae</em> , un número dado de elementos a una nueva matriz, dejando la matriz a la que se llama sin tocar. <code>slice()</code> toma solo 2 parámetros: el primero es el índice para comenzar la extracción y el segundo es el índice para detener la extracción (la extracción ocurrirá hasta, pero sin incluir el elemento en este índice). Considera esto:
|
||||
<blockquote>let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];<br><br>let todaysWeather = weatherConditions.slice(1, 3);<br>// todaysWeather equals ['snow', 'sleet'];<br>// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']<br></blockquote>
|
||||
En efecto, hemos creado una nueva matriz extrayendo elementos de una matriz existente.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>forecast</code> , que toma una matriz como argumento. Modifique la función utilizando <code>slice()</code> para extraer información de la matriz de argumentos y devuelva una nueva matriz que contenga los elementos <code>'warm'</code> y <code>'sunny'</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>forecast</code> debería devolver <code>["warm", "sunny"]'</code>
|
||||
testString: 'assert.deepEqual(forecast(["cold", "rainy", "warm", "sunny", "cool", "thunderstorms"]), ["warm", "sunny"], "<code>forecast</code> should return <code>["warm", "sunny"]");'
|
||||
- text: La función de <code>forecast</code> debe utilizar el método <code>slice()</code>
|
||||
testString: 'assert(/\.slice\(/.test(code), "The <code>forecast</code> function should utilize the <code>slice()</code> method");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function forecast(arr) {
|
||||
// change code below this line
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
// do not change code below this line
|
||||
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b16
|
||||
title: Create complex multi-dimensional arrays
|
||||
localeTitle: Crear complejos arreglos multidimensionales.
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
impresionante! ¡Acabas de aprender un montón de arreglos! Este ha sido un resumen de nivel bastante alto, y hay mucho más que aprender sobre el trabajo con matrices, muchas de las cuales veremos en secciones posteriores. Pero antes de pasar a mirar <dfn>Objetos</dfn> , echemos un vistazo más y veamos cómo los arreglos pueden volverse un poco más complejos de lo que hemos visto en desafíos anteriores.
|
||||
Una de las características más poderosas cuando se piensa en los arreglos como estructuras de datos, es que los arreglos pueden contener, o incluso estar completamente compuestos de otros arreglos. Hemos visto matrices que contienen matrices en desafíos anteriores, pero bastante simples. Sin embargo, las matrices pueden contener una profundidad infinita de matrices que pueden contener otras matrices, cada una con sus propios niveles arbitrarios de profundidad, y así sucesivamente. De esta manera, una matriz puede convertirse muy rápidamente en una estructura de datos muy compleja, conocida como una matriz <dfn>multidimensional</dfn> o anidada. Considera el siguiente ejemplo:
|
||||
<blockquote>let nestedArray = [ // top, or first level - the outer most array<br> ['deep'], // an array within an array, 2 levels of depth<br> [<br> ['deeper'], ['deeper'] // 2 arrays nested 3 levels deep<br> ],<br> [<br> [<br> ['deepest'], ['deepest'] // 2 arrays nested 4 levels deep<br> ],<br> [<br> [<br> ['deepest-est?'] // an array nested 5 levels deep<br> ]<br> ]<br> ]<br>];</blockquote>
|
||||
Si bien este ejemplo puede parecer complicado, este nivel de complejidad no es inaudito, o incluso inusual, cuando se trata de grandes cantidades de datos.
|
||||
Sin embargo, aún podemos acceder fácilmente a los niveles más profundos de una matriz de este complejo con notación de corchete:
|
||||
<blockquote>console.log(nestedArray[2][1][0][0][0]);<br>// logs: deepest-est?</blockquote>
|
||||
Y ahora que sabemos dónde está ese dato, podemos restablecerlo si necesitamos:
|
||||
<blockquote>nestedArray[2][1][0][0][0] = 'deeper still';<br><br>console.log(nestedArray[2][1][0][0][0]);<br>// now logs: deeper still</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una variable, <code>myNestedArray</code> , igual a una matriz. Modifique <code>myNestedArray</code> , utilizando cualquier combinación de <dfn>cadenas</dfn> , <dfn>números</dfn> y <dfn>valores booleanos</dfn> para los elementos de datos, de modo que tenga exactamente cinco niveles de profundidad (recuerde, la matriz más externa es el nivel 1). En algún lugar en el tercer nivel, incluye la cadena <code>'deep'</code> , en el cuarto nivel, incluyen la cadena <code>'deeper'</code> , y en el quinto nivel, incluyen la cadena <code>'deepest'</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>myNestedArray</code> debe contener solo números, booleanos y cadenas como elementos de datos'
|
||||
testString: 'assert.strictEqual((function(arr) { let flattened = (function flatten(arr) { const flat = [].concat(...arr); return flat.some (Array.isArray) ? flatten(flat) : flat; })(arr); for (let i = 0; i < flattened.length; i++) { if ( typeof flattened[i] !== "number" && typeof flattened[i] !== "string" && typeof flattened[i] !== "boolean") { return false } } return true })(myNestedArray), true, "<code>myNestedArray</code> should contain only numbers, booleans, and strings as data elements");'
|
||||
- text: <code>myNestedArray</code> debe tener exactamente 5 niveles de profundidad
|
||||
testString: 'assert.strictEqual((function(arr) {let depth = 0;function arrayDepth(array, i, d) { if (Array.isArray(array[i])) { arrayDepth(array[i], 0, d + 1);} else { depth = (d > depth) ? d : depth;}if (i < array.length) { arrayDepth(array, i + 1, d);} }arrayDepth(arr, 0, 0);return depth;})(myNestedArray), 4, "<code>myNestedArray</code> should have exactly 5 levels of depth");'
|
||||
- text: <code>myNestedArray</code> debe contener exactamente una aparición de la cadena <code>"deep"</code> en una matriz anidada con 3 niveles de profundidad
|
||||
testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deep").length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deep")[0] === 2, "<code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deep"</code> on an array nested 3 levels deep");'
|
||||
- text: <code>myNestedArray</code> debe contener exactamente una aparición de la cadena <code>"deeper"</code> deep <code>"deeper"</code> en una matriz anidada con 4 niveles de profundidad
|
||||
testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deeper").length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deeper")[0] === 3, "<code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deeper"</code> on an array nested 4 levels deep");'
|
||||
- text: <code>myNestedArray</code> debe contener exactamente una aparición de la cadena <code>"deepest"</code> en una matriz anidada a 5 niveles de profundidad
|
||||
testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deepest").length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deepest")[0] === 4, "<code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deepest"</code> on an array nested 5 levels deep");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let myNestedArray = [
|
||||
// change code below this line
|
||||
['unshift', false, 1, 2, 3, 'complex', 'nested'],
|
||||
['loop', 'shift', 6, 7, 1000, 'method'],
|
||||
['concat', false, true, 'spread', 'array'],
|
||||
['mutate', 1327.98, 'splice', 'slice', 'push'],
|
||||
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
|
||||
// change code above this line
|
||||
];
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1e
|
||||
title: Generate an Array of All Object Keys with Object.keys()
|
||||
localeTitle: Generar una matriz de todas las claves de objeto con Object.keys ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
También podemos generar una matriz que contiene todas las claves almacenadas en un objeto usando el método <code>Object.keys()</code> y pasando un objeto como argumento. Esto devolverá una matriz con cadenas que representan cada propiedad en el objeto. Nuevamente, no habrá un orden específico para las entradas en la matriz.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Termine de escribir la función <code>getArrayOfUsers</code> para que devuelva una matriz que contenga todas las propiedades en el objeto que recibe como argumento.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'El objeto de los <code>users</code> solo contiene las claves <code>Alan</code> , <code>Jeff</code> , <code>Sarah</code> y <code>Ryan</code> '
|
||||
testString: 'assert("Alan" in users && "Jeff" in users && "Sarah" in users && "Ryan" in users && Object.keys(users).length === 4, "The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>");'
|
||||
- text: La función <code>getArrayOfUsers</code> devuelve una matriz que contiene todas las claves en el objeto de los <code>users</code>
|
||||
testString: 'assert((function() { users.Sam = {}; users.Lewis = {}; let R = getArrayOfUsers(users); return (R.indexOf("Alan") !== -1 && R.indexOf("Jeff") !== -1 && R.indexOf("Sarah") !== -1 && R.indexOf("Ryan") !== -1 && R.indexOf("Sam") !== -1 && R.indexOf("Lewis") !== -1); })() === true, "The <code>getArrayOfUsers</code> function returns an array which contains all the keys in the <code>users</code> object");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let users = {
|
||||
Alan: {
|
||||
age: 27,
|
||||
online: false
|
||||
},
|
||||
Jeff: {
|
||||
age: 32,
|
||||
online: true
|
||||
},
|
||||
Sarah: {
|
||||
age: 48,
|
||||
online: false
|
||||
},
|
||||
Ryan: {
|
||||
age: 19,
|
||||
online: true
|
||||
}
|
||||
};
|
||||
|
||||
function getArrayOfUsers(obj) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
}
|
||||
|
||||
console.log(getArrayOfUsers(users));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b15
|
||||
title: Iterate Through All an Array's Items Using For Loops
|
||||
localeTitle: Iterar a través de todos los elementos de una matriz utilizando bucles for
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
A veces, cuando se trabaja con matrices, es muy útil poder recorrer cada elemento para encontrar uno o más elementos que podríamos necesitar, o manipular una matriz en función de qué elementos de datos cumplen un determinado conjunto de criterios. JavaScript ofrece varios métodos integrados que se repiten en matrices de maneras ligeramente diferentes para lograr resultados diferentes (como <code>every()</code> , para <code>forEach()</code> , <code>map()</code> , etc.), sin embargo, la técnica es más flexible y nos ofrece la mejor cantidad de control es un simple <code>for</code> bucle.
|
||||
Considera lo siguiente:
|
||||
<blockquote>function greaterThanTen(arr) {<br> let newArr = [];<br> for (let i = 0; i < arr.length; i++) {<br> if (arr[i] > 10) {<br> newArr.push(arr[i]);<br> }<br> }<br> return newArr;<br>}<br><br>greaterThanTen([2, 12, 8, 14, 80, 0, 1]);<br>// returns [12, 14, 80]</blockquote>
|
||||
Usando un bucle <code>for</code> , esta función recorre y accede a cada elemento de la matriz, y lo somete a una prueba simple que hemos creado. De esta manera, hemos determinado fácil y programáticamente qué elementos de datos son más grandes que <code>10</code> , y hemos devuelto una nueva matriz que contiene esos elementos.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>filteredArray</code> , que toma <code>arr</code> , una matriz anidada, y <code>elem</code> como argumentos, y devuelve una nueva matriz. <code>elem</code> representa un elemento que puede o no estar presente en una o más de las matrices anidadas dentro de <code>arr</code> . Modifique la función, utilizando un bucle <code>for</code> , para devolver una versión filtrada de la matriz pasada de manera que se haya eliminado cualquier matriz anidada dentro de <code>arr</code> contenga <code>elem</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)</code> debe devolver <code>[ [10, 8, 3], [14, 6, 23] ]</code> '
|
||||
testString: 'assert.deepEqual(filteredArray([ [10, 8, 3], [14, 6, 23], [3, 18, 6] ], 18), [[10, 8, 3], [14, 6, 23]], "<code>filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)</code> should return <code>[ [10, 8, 3], [14, 6, 23] ]</code>");'
|
||||
- text: ' <code>filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)</code> debe devolver <code>[ ["flutes", 4] ]</code> '
|
||||
testString: 'assert.deepEqual(filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2), [["flutes", 4]], "<code>filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)</code> should return <code>[ ["flutes", 4] ]</code>");'
|
||||
- text: ' <code>filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")</code> debe devolver <code>[ ["amy", "beth", "sam"] ]</code> '
|
||||
testString: 'assert.deepEqual(filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter"), [["amy", "beth", "sam"]], "<code>filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")</code> should return <code>[ ["amy", "beth", "sam"] ]</code>");'
|
||||
- text: ' <code>filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)</code> debe devolver <code>[ ]</code> '
|
||||
testString: 'assert.deepEqual(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3), [], "<code>filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)</code> should return <code>[ ]</code>");'
|
||||
- text: El <code>filteredArray</code> función debe utilizar un <code>for</code> bucle
|
||||
testString: 'assert.notStrictEqual(filteredArray.toString().search(/for/), -1, "The <code>filteredArray</code> function should utilize a <code>for</code> loop");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function filteredArray(arr, elem) {
|
||||
let newArr = [];
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
return newArr;
|
||||
}
|
||||
|
||||
// change code here to test different cases:
|
||||
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,81 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1f
|
||||
title: Modify an Array Stored in an Object
|
||||
localeTitle: Modificar una matriz almacenada en un objeto
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Ahora has visto todas las operaciones básicas para objetos JavaScript. Puede agregar, modificar y eliminar pares clave-valor, verificar si existen claves e iterar sobre todas las claves en un objeto. A medida que continúe aprendiendo JavaScript, verá aplicaciones de objetos aún más versátiles. Además, las lecciones opcionales de Estructuras de datos avanzadas más adelante en el plan de estudios también cubren los objetos <dfn>Map</dfn> y <dfn>Set de</dfn> ES6, los cuales son similares a los objetos comunes pero ofrecen algunas características adicionales. ¡Ahora que ha aprendido los conceptos básicos de matrices y objetos, está completamente preparado para comenzar a abordar problemas más complejos utilizando JavaScript!
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Eche un vistazo al objeto que hemos proporcionado en el editor de código. El objeto de <code>user</code> contiene tres claves. La clave de <code>data</code> contiene cinco claves, una de las cuales contiene una gran variedad de <code>friends</code> . A partir de esto, puede ver cómo los objetos flexibles son como estructuras de datos. Hemos empezado a escribir una función <code>addFriend</code> . Termine de escribirlo para que tome un objeto de <code>user</code> y agregue el nombre del argumento de <code>friend</code> a la matriz almacenada en <code>user.data.friends</code> y devuelva esa matriz.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'El objeto de <code>user</code> tiene <code>name</code> , <code>age</code> y claves de <code>data</code> '
|
||||
testString: 'assert("name" in user && "age" in user && "data" in user, "The <code>user</code> object has <code>name</code>, <code>age</code>, and <code>data</code> keys");'
|
||||
- text: La función <code>addFriend</code> acepta un objeto de <code>user</code> y una cadena de <code>friend</code> como argumentos y agrega el amigo a la matriz de <code>friends</code> en el objeto de <code>user</code>
|
||||
testString: 'assert((function() { let L1 = user.data.friends.length; addFriend(user, "Sean"); let L2 = user.data.friends.length; return (L2 === L1 + 1); })(), "The <code>addFriend</code> function accepts a <code>user</code> object and a <code>friend</code> string as arguments and adds the friend to the array of <code>friends</code> in the <code>user</code> object");'
|
||||
- text: ' <code>addFriend(user, "Pete")</code> debe devolver <code>["Sam", "Kira", "Tomo", "Pete"]</code> '
|
||||
testString: 'assert.deepEqual((function() { delete user.data.friends; user.data.friends = ["Sam", "Kira", "Tomo"]; return addFriend(user, "Pete") })(), ["Sam", "Kira", "Tomo", "Pete"], "<code>addFriend(user, "Pete")</code> should return <code>["Sam", "Kira", "Tomo", "Pete"]</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let user = {
|
||||
name: 'Kenneth',
|
||||
age: 28,
|
||||
data: {
|
||||
username: 'kennethCodesAllDay',
|
||||
joinDate: 'March 26, 2016',
|
||||
organization: 'freeCodeCamp',
|
||||
friends: [
|
||||
'Sam',
|
||||
'Kira',
|
||||
'Tomo'
|
||||
],
|
||||
location: {
|
||||
city: 'San Francisco',
|
||||
state: 'CA',
|
||||
country: 'USA'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function addFriend(userObj, friend) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
}
|
||||
|
||||
console.log(addFriend(user, 'Pete'));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b19
|
||||
title: Modify an Object Nested Within an Object
|
||||
localeTitle: Modificar un objeto anidado dentro de un objeto
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Ahora veamos un objeto un poco más complejo. Las propiedades de los objetos se pueden anidar a una profundidad arbitraria, y sus valores pueden ser cualquier tipo de datos admitidos por JavaScript, incluidas las matrices e incluso otros objetos. Considera lo siguiente:
|
||||
<blockquote>let nestedObject = {<br> id: 28802695164,<br> date: 'December 31, 2016',<br> data: {<br> totalUsers: 99,<br> online: 80,<br> onlineStatus: {<br> active: 67,<br> away: 13<br> }<br> }<br>};</blockquote>
|
||||
<code>nestedObject</code> tiene tres claves únicas: <code>id</code> , cuyo valor es un número, la <code>date</code> cuyo valor es una cadena y los <code>data</code> , cuyo valor es un objeto que tiene otro objeto anidado dentro de él. Si bien las estructuras pueden volverse complejas rápidamente, aún podemos usar las mismas notaciones para acceder a la información que necesitamos.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Aquí hemos definido un objeto, <code>userActivity</code> , que incluye otro objeto anidado dentro de él. Puede modificar las propiedades de este objeto anidado de la misma manera que modificó las propiedades en el último desafío. Establezca el valor de la clave en <code>online</code> en <code>45</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>userActivity</code> tiene <code>id</code> , <code>date</code> y propiedades de <code>data</code> '
|
||||
testString: 'assert("id" in userActivity && "date" in userActivity && "data" in userActivity, "<code>userActivity</code> has <code>id</code>, <code>date</code> and <code>data</code> properties");'
|
||||
- text: <code>userActivity</code> tiene una clave de <code>data</code> configurada para un objeto con las teclas <code>totalUsers</code> y en <code>online</code>
|
||||
testString: 'assert("totalUsers" in userActivity.data && "online" in userActivity.data, "<code>userActivity</code> has a <code>data</code> key set to an object with keys <code>totalUsers</code> and <code>online</code>");'
|
||||
- text: La propiedad en <code>online</code> anidada en la clave de <code>data</code> de <code>userActivity</code> debe establecer en <code>45</code>
|
||||
testString: 'assert(userActivity.data.online === 45, "The <code>online</code> property nested in the <code>data</code> key of <code>userActivity</code> should be set to <code>45</code>");'
|
||||
- text: La propiedad en <code>online</code> se establece mediante notación de punto o corchete
|
||||
testString: 'assert.strictEqual(code.search(/online: 45/), -1, "The <code>online</code> property is set using dot or bracket notation");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let userActivity = {
|
||||
id: 23894201352,
|
||||
date: 'January 1, 2017',
|
||||
data: {
|
||||
totalUsers: 51,
|
||||
online: 42
|
||||
}
|
||||
};
|
||||
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
|
||||
console.log(userActivity);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0f
|
||||
title: Remove Items from an Array with pop() and shift()
|
||||
localeTitle: Eliminar elementos de una matriz con pop () y shift ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Tanto <code>push()</code> como <code>unshift()</code> tienen métodos correspondientes que son opuestos casi funcionales: <code>pop()</code> y <code>shift()</code> . Como ya habrá adivinado, en lugar de agregar, <code>pop()</code> <em>elimina</em> un elemento del final de una matriz, mientras que <code>shift()</code> elimina un elemento desde el principio. La diferencia clave entre <code>pop()</code> y <code>shift()</code> y sus primos <code>push()</code> y <code>unshift()</code> , es que ninguno de los dos métodos toma parámetros, y cada uno solo permite que una matriz sea modificada por un solo elemento a la vez.
|
||||
Echemos un vistazo:
|
||||
<blockquote>let greetings = ['whats up?', 'hello', 'see ya!'];<br><br>greetings.pop();<br>// now equals ['whats up?', 'hello']<br><br>greetings.shift();<br>// now equals ['hello']</blockquote>
|
||||
También podemos devolver el valor del elemento eliminado con uno de estos métodos:
|
||||
<blockquote>let popped = greetings.pop();<br>// returns 'hello'<br>// greetings now equals []</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>popShift</code> , que toma una matriz como argumento y devuelve una nueva matriz. Modifique la función, utilizando <code>pop()</code> y <code>shift()</code> , para eliminar el primer y último elemento de la matriz de argumentos, y asigne los elementos eliminados a sus variables correspondientes, de modo que la matriz devuelta contenga sus valores.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>popShift(["challenge", "is", "not", "complete"])</code> debe devolver <code>["challenge", "complete"]</code> '
|
||||
testString: 'assert.deepEqual(popShift(["challenge", "is", "not", "complete"]), ["challenge", "complete"], "<code>popShift(["challenge", "is", "not", "complete"])</code> should return <code>["challenge", "complete"]</code>");'
|
||||
- text: La función <code>popShift</code> debería utilizar el método <code>pop()</code>
|
||||
testString: 'assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1, "The <code>popShift</code> function should utilize the <code>pop()</code> method");'
|
||||
- text: La función <code>popShift</code> debería utilizar el método <code>shift()</code>
|
||||
testString: 'assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1, "The <code>popShift</code> function should utilize the <code>shift()</code> method");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function popShift(arr) {
|
||||
let popped; // change this line
|
||||
let shifted; // change this line
|
||||
return [shifted, popped];
|
||||
}
|
||||
|
||||
// do not change code below this line
|
||||
console.log(popShift(['challenge', 'is', 'not', 'complete']));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b10
|
||||
title: Remove Items Using splice()
|
||||
localeTitle: Quitar elementos utilizando empalme ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Bien, hemos aprendido cómo eliminar elementos del principio y el final de los arreglos usando <code>shift()</code> y <code>pop()</code> , pero ¿qué pasa si queremos eliminar un elemento de algún lugar en el medio? ¿O eliminar más de un elemento a la vez? Bueno, ahí es donde entra <code>splice()</code> . <code>splice()</code> nos permite hacer precisamente eso: <strong>eliminar cualquier número de elementos consecutivos</strong> de cualquier lugar en una matriz.
|
||||
<code>splice()</code> puede tomar hasta 3 parámetros, pero por ahora, nos enfocaremos solo en los primeros 2. Los primeros dos parámetros de <code>splice()</code> son enteros que representan índices, o posiciones, de la matriz que <code>splice()</code> es siendo llamado. Y recuerde, las matrices tienen <em>un índice de cero</em> , por lo que para indicar el primer elemento de una matriz, usaríamos <code>0</code> . El primer parámetro de <code>splice()</code> representa el índice en la matriz a partir de la cual comenzar a eliminar elementos, mientras que el segundo parámetro indica el número de elementos a eliminar. Por ejemplo:
|
||||
<blockquote>let array = ['today', 'was', 'not', 'so', 'great'];<br><br>array.splice(2, 2);<br>// remove 2 elements beginning with the 3rd element<br>// array now equals ['today', 'was', 'great']</blockquote>
|
||||
<code>splice()</code> no solo modifica la matriz en la que se llama, sino que también devuelve una nueva matriz que contiene el valor de los elementos eliminados:
|
||||
<blockquote>let array = ['I', 'am', 'feeling', 'really', 'happy'];<br><br>let newArray = array.splice(3, 2);<br>// newArray equals ['really', 'happy']</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una función, <code>sumOfTen</code> , que toma una matriz como argumento y devuelve la suma de los elementos de esa matriz. Modifique la función, usando <code>splice()</code> , para que devuelva un valor de <code>10</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>sumOfTen</code> debe devolver 10
|
||||
testString: 'assert.strictEqual(sumOfTen([2, 5, 1, 5, 2, 1]), 10, "<code>sumOfTen</code> should return 10");'
|
||||
- text: La función <code>sumOfTen</code> debe utilizar el método <code>splice()</code>
|
||||
testString: 'assert.notStrictEqual(sumOfTen.toString().search(/\.splice\(/), -1, "The <code>sumOfTen</code> function should utilize the <code>splice()</code> method");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function sumOfTen(arr) {
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
return arr.reduce((a, b) => a + b);
|
||||
}
|
||||
|
||||
// do not change code below this line
|
||||
console.log(sumOfTen([2, 5, 1, 5, 2, 1]));
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,63 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b20
|
||||
title: Use an Array to Store a Collection of Data
|
||||
localeTitle: Utilice una matriz para almacenar una colección de datos
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
A continuación se muestra un ejemplo de la implementación más simple de una estructura de datos de matriz. Esto se conoce como una <dfn>matriz unidimensional</dfn> , lo que significa que solo tiene un nivel, o que no tiene ninguna otra matriz anidada dentro de ella. Observe que contiene <dfn>valores booleanos</dfn> , <dfn>cadenas</dfn> y <dfn>números</dfn> , entre otros tipos de datos de JavaScript válidos:
|
||||
<blockquote>let simpleArray = ['one', 2, 'three’, true, false, undefined, null];<br>console.log(simpleArray.length);<br>// logs 7</blockquote>
|
||||
Todas las matrices tienen una propiedad de longitud que, como se muestra arriba, se puede acceder muy fácilmente con la sintaxis <code>Array.length</code> .
|
||||
Una implementación más compleja de una matriz se puede ver a continuación. Esto se conoce como una <dfn>matriz multidimensional</dfn> o una matriz que contiene otras matrices. Tenga en cuenta que esta matriz también contiene <dfn>objetos</dfn> JavaScript, que examinaremos detenidamente en nuestra próxima sección, pero por ahora, todo lo que necesita saber es que las matrices también son capaces de almacenar objetos complejos.
|
||||
<blockquote>let complexArray = [<br> [<br> {<br> one: 1,<br> two: 2<br> },<br> {<br> three: 3,<br> four: 4<br> }<br> ],<br> [<br> {<br> a: "a",<br> b: "b"<br> },<br> {<br> c: "c",<br> d: “d”<br> }<br> ]<br>];</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Hemos definido una variable llamada <code>yourArray</code> . Complete la declaración asignando una matriz de al menos 5 elementos de longitud a la variable <code>yourArray</code> . Su matriz debe contener al menos una <dfn>cadena</dfn> , un <dfn>número</dfn> y un <dfn>booleano</dfn> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: yourArray es una matriz
|
||||
testString: 'assert.strictEqual(Array.isArray(yourArray), true, "yourArray is an array");'
|
||||
- text: <code class = "notranslate"> yourArray </code> tiene al menos 5 elementos
|
||||
testString: 'assert.isAtLeast(yourArray.length, 5, "<code>yourArray</code> is at least 5 elements long");'
|
||||
- text: <code class = "notranslate"> yourArray </code> contiene al menos un <code class = "notranslate"> boolean </code>
|
||||
testString: 'assert(yourArray.filter( el => typeof el === "boolean").length >= 1, "<code>yourArray</code> contains at least one <code>boolean</code>");'
|
||||
- text: <code class = "notranslate"> yourArray </code> contiene al menos un <code class = "notranslate"> number </code>
|
||||
testString: 'assert(yourArray.filter( el => typeof el === "number").length >= 1, "<code>yourArray</code> contains at least one <code>number</code>");'
|
||||
- text: <code class = "notranslate"> yourArray </code> contiene al menos una <code class = "notranslate"> string </code>
|
||||
testString: 'assert(yourArray.filter( el => typeof el === "string").length >= 1, "<code>yourArray</code> contains at least one <code>string</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let yourArray; // change this line
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1b
|
||||
title: Use the delete Keyword to Remove Object Properties
|
||||
localeTitle: Utilice la palabra clave delete para eliminar las propiedades del objeto
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Ahora ya sabes qué son los objetos y sus características y ventajas básicas. En resumen, son tiendas de valor clave que proporcionan una forma flexible e intuitiva de estructurar los datos <strong><em>y</em></strong> proporcionan un tiempo de búsqueda muy rápido. A lo largo del resto de estos desafíos, describiremos varias operaciones comunes que puede realizar en objetos para que pueda sentirse cómodo aplicando estas estructuras de datos útiles en sus programas.
|
||||
En desafíos anteriores, hemos agregado y modificado los pares clave-valor de un objeto. Aquí veremos cómo podemos <em>eliminar</em> un par clave-valor de un objeto.
|
||||
Repasemos nuestro ejemplo de objeto de <code>foods</code> una última vez. Si quisiéramos eliminar la clave de las <code>apples</code> , podemos eliminarla usando la palabra clave <code>delete</code> así:
|
||||
<blockquote>delete foods.apples;</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use la palabra clave delete para eliminar las teclas de <code>oranges</code> , <code>plums</code> y <code>strawberries</code> del objeto de <code>foods</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'El objeto de <code>foods</code> solo tiene tres claves: <code>apples</code> , <code>grapes</code> y <code>bananas</code> '
|
||||
testString: 'assert(!foods.hasOwnProperty("oranges") && !foods.hasOwnProperty("plums") && !foods.hasOwnProperty("strawberries") && Object.keys(foods).length === 3, "The <code>foods</code> object only has three keys: <code>apples</code>, <code>grapes</code>, and <code>bananas</code>");'
|
||||
- text: 'Las claves de <code>oranges</code> , <code>plums</code> y <code>strawberries</code> se eliminan usando <code>delete</code> '
|
||||
testString: 'assert(code.search(/oranges:/) !== -1 && code.search(/plums:/) !== -1 && code.search(/strawberries:/) !== -1, "The <code>oranges</code>, <code>plums</code>, and <code>strawberries</code> keys are removed using <code>delete</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
let foods = {
|
||||
apples: 25,
|
||||
oranges: 32,
|
||||
plums: 28,
|
||||
bananas: 13,
|
||||
grapes: 35,
|
||||
strawberries: 27
|
||||
};
|
||||
|
||||
// change code below this line
|
||||
|
||||
// change code above this line
|
||||
|
||||
console.log(foods);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ca
|
||||
title: Access Array Data with Indexes
|
||||
localeTitle: Acceso a datos de matriz con índices
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/access-array-data-with-indexes'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Podemos acceder a los datos dentro de las matrices utilizando <code>indexes</code> .
|
||||
índices de matriz se escriben en la misma notación de corchete que usan las cadenas, excepto que en lugar de especificar un carácter, están especificando una entrada en la matriz. Al igual que las cadenas, las matrices utilizan indización <dfn>basada en cero</dfn> , por lo que el primer elemento de una matriz es el elemento <code>0</code> .
|
||||
<strong>Ejemplo</strong>
|
||||
<blockquote>var array = [50,60,70];<br>array[0]; // equals 50<br>var data = array[1]; // equals 60</blockquote>
|
||||
<strong>Nota</strong> <br> No debe haber espacios entre el nombre de la matriz y los corchetes, como la <code>array [0]</code> . Aunque JavaScript puede procesar esto correctamente, esto puede confundir a otros programadores que leen su código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cree una variable llamada <code>myData</code> y <code>myArray</code> para que sea igual al primer valor de <code>myArray</code> usando notación de corchete.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>myData</code> debe ser igual al primer valor de <code>myArray</code> .
|
||||
testString: 'assert((function(){if(typeof myArray !== "undefined" && typeof myData !== "undefined" && myArray[0] === myData){return true;}else{return false;}})(), "The variable <code>myData</code> should equal the first value of <code>myArray</code>.");'
|
||||
- text: Se debe acceder a los datos en la variable <code>myArray</code> usando notación de corchetes.
|
||||
testString: 'assert((function(){if(code.match(/\s*=\s*myArray\[0\]/g)){return true;}else{return false;}})(), "The data in variable <code>myArray</code> should be accessed using bracket notation.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourArray = [50,60,70];
|
||||
var ourData = ourArray[0]; // equals 50
|
||||
|
||||
// Setup
|
||||
var myArray = [50,60,70];
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myArray = [50,60,70];
|
||||
var myData = myArray[0];
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: 56592a60ddddeae28f7aa8e1
|
||||
title: Access Multi-Dimensional Arrays With Indexes
|
||||
localeTitle: Acceder a matrices multidimensionales con índices
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/access-array-data-with-indexes'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Una forma de pensar en una matriz <dfn>multidimensional</dfn> es como una <em>matriz de matrices</em> . Cuando usa corchetes para acceder a su matriz, el primer conjunto de corchetes se refiere a las entradas en la matriz más externa (el primer nivel), y cada par adicional de corchetes se refiere al siguiente nivel de entradas adentro.
|
||||
<strong>Ejemplo</strong>
|
||||
<blockquote>var arr = [<br> [1,2,3],<br> [4,5,6],<br> [7,8,9],<br> [[10,11,12], 13, 14]<br>];<br>arr[3]; // equals [[10,11,12], 13, 14]<br>arr[3][0]; // equals [10,11,12]<br>arr[3][0][1]; // equals 11</blockquote>
|
||||
<strong>Nota</strong> <br> No debe haber espacios entre el nombre de la matriz y los corchetes, como la <code>array [0][0]</code> e incluso esta <code>array [0] [0]</code> no está permitida. Aunque JavaScript puede procesar esto correctamente, esto puede confundir a otros programadores que leen su código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Usando la notación de corchetes, seleccione un elemento de <code>myArray</code> para que <code>myData</code> sea igual a <code>8</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myData</code> debe ser igual a <code>8</code> .
|
||||
testString: 'assert(myData === 8, "<code>myData</code> should be equal to <code>8</code>.");'
|
||||
- text: Debe usar la notación de corchetes para leer el valor correcto de <code>myArray</code> .
|
||||
testString: 'assert(/myArray\[2\]\[1\]/g.test(code) && !/myData\s*=\s*(?:.*[-+*/%]|\d)/g.test(code), "You should be using bracket notation to read the correct value from <code>myArray</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
|
||||
// Only change code below this line.
|
||||
var myData = myArray[0][0];
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
var myData = myArray[2][1];
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,110 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cd
|
||||
title: Accessing Nested Arrays
|
||||
localeTitle: Acceso a matrices anidadas
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/access-array-data-with-indexes'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Como hemos visto en ejemplos anteriores, los objetos pueden contener tanto objetos anidados como matrices anidadas. Al igual que para acceder a objetos anidados, la notación de paréntesis de arrays se puede encadenar para acceder a arrays anidados.
|
||||
Aquí hay un ejemplo de cómo acceder a una matriz anidada:
|
||||
<blockquote>var ourPets = [<br> {<br> animalType: "cat",<br> names: [<br> "Meowzer",<br> "Fluffy",<br> "Kit-Cat"<br> ]<br> },<br> {<br> animalType: "dog",<br> names: [<br> "Spot",<br> "Bowser",<br> "Frankie"<br> ]<br> }<br>];<br>ourPets[0].names[1]; // "Fluffy"<br>ourPets[1].names[0]; // "Spot"</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Recupere el segundo árbol de la variable <code>myPlants</code> usando el punto de objeto y la notación de corchete de matriz.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>secondTree</code> debe ser igual a "pino"
|
||||
testString: 'assert(secondTree === "pine", "<code>secondTree</code> should equal "pine"");'
|
||||
- text: Use la notación de puntos y corchetes para acceder a <code>myPlants</code>
|
||||
testString: 'assert(/=\s*myPlants\[1\].list\[1\]/.test(code), "Use dot and bracket notation to access <code>myPlants</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var secondTree = ""; // Change this line
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var secondTree = myPlants[1].list[1];
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cc
|
||||
title: Accessing Nested Objects
|
||||
localeTitle: Accediendo a objetos anidados
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/accessing-nested-objects-in-json'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Se puede acceder a las sub-propiedades de los objetos encadenando la notación de punto o corchete.
|
||||
Aquí hay un objeto anidado:
|
||||
<blockquote>var ourStorage = {<br> "desk": {<br> "drawer": "stapler"<br> },<br> "cabinet": {<br> "top drawer": { <br> "folder1": "a file",<br> "folder2": "secrets"<br> },<br> "bottom drawer": "soda"<br> }<br>};<br>ourStorage.cabinet["top drawer"].folder2; // "secrets"<br>ourStorage.desk.drawer; // "stapler"</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Acceda al objeto <code>myStorage</code> y asigne el contenido de la propiedad de la <code>glove box</code> a la variable <code>gloveBoxContents</code> . Utilice la notación de corchete para las propiedades con un espacio en su nombre.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>gloveBoxContents</code> debe ser igual a "mapas"
|
||||
testString: 'assert(gloveBoxContents === "maps", "<code>gloveBoxContents</code> should equal "maps"");'
|
||||
- text: Usa la notación de puntos y corchetes para acceder a <code>myStorage</code>
|
||||
testString: 'assert(/=\s*myStorage\.car\.inside\[\s*("|")glove box\1\s*\]/g.test(code), "Use dot and bracket notation to access <code>myStorage</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myStorage = {
|
||||
"car": {
|
||||
"inside": {
|
||||
"glove box": "maps",
|
||||
"passenger seat": "crumbs"
|
||||
},
|
||||
"outside": {
|
||||
"trunk": "jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var gloveBoxContents = undefined; // Change this line
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myStorage = {
|
||||
"car":{
|
||||
"inside":{
|
||||
"glove box":"maps",
|
||||
"passenger seat":"crumbs"
|
||||
},
|
||||
"outside":{
|
||||
"trunk":"jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
var gloveBoxContents = myStorage.car.inside["glove box"];
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c8
|
||||
title: Accessing Object Properties with Bracket Notation
|
||||
localeTitle: Acceso a las propiedades del objeto con notación de corchete
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/accessing-objects-properties-with-bracket-notation'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
La segunda forma de acceder a las propiedades de un objeto es la notación de corchetes ( <code>[]</code> ). Si la propiedad del objeto al que intenta acceder tiene un espacio en su nombre, deberá utilizar la notación de corchetes.
|
||||
Sin embargo, aún puede usar la notación de corchete en las propiedades del objeto sin espacios.
|
||||
Aquí hay una muestra del uso de la notación de corchetes para leer la propiedad de un objeto:
|
||||
<blockquote>var myObj = {<br> "Space Name": "Kirk",<br> "More Space": "Spock",<br> "NoSpace": "USS Enterprise"<br>};<br>myObj["Space Name"]; // Kirk<br>myObj['More Space']; // Spock<br>myObj["NoSpace"]; // USS Enterprise</blockquote>
|
||||
Tenga en cuenta que los nombres de propiedades con espacios en ellos deben estar entre comillas (simple o doble).
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Lea los valores de las propiedades <code>"an entree"</code> y <code>"the drink"</code> de <code>testObj</code> utilizando la notación de corchetes y asignarlos a <code>entreeValue</code> y <code>drinkValue</code> respectivamente.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>entreeValue</code> debe ser una cadena
|
||||
testString: 'assert(typeof entreeValue === "string" , "<code>entreeValue</code> should be a string");'
|
||||
- text: El valor de <code>entreeValue</code> debe ser <code>"hamburger"</code>
|
||||
testString: 'assert(entreeValue === "hamburger" , "The value of <code>entreeValue</code> should be <code>"hamburger"</code>");'
|
||||
- text: <code>drinkValue</code> debe ser una cadena
|
||||
testString: 'assert(typeof drinkValue === "string" , "<code>drinkValue</code> should be a string");'
|
||||
- text: El valor de <code>drinkValue</code> debe ser <code>"water"</code>
|
||||
testString: 'assert(drinkValue === "water" , "The value of <code>drinkValue</code> should be <code>"water"</code>");'
|
||||
- text: Usted debe usar la notación de soporte dos veces
|
||||
testString: 'assert(code.match(/testObj\s*?\[("|")[^""]+\1\]/g).length > 1, "You should use bracket notation twice");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var entreeValue = testObj; // Change this line
|
||||
var drinkValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
var entreeValue = testObj["an entree"];
|
||||
var drinkValue = testObj['the drink'];
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c7
|
||||
title: Accessing Object Properties with Dot Notation
|
||||
localeTitle: Acceso a las propiedades del objeto con notación de puntos
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Hay dos formas de acceder a las propiedades de un objeto: notación de puntos ( <code>.</code> ) Y notación de corchetes ( <code>[]</code> ), similar a una matriz.
|
||||
notación de puntos es lo que usa cuando conoce el nombre de la propiedad a la que intenta acceder con anticipación.
|
||||
Aquí hay una muestra de cómo usar la notación de puntos ( <code>.</code> ) Para leer la propiedad de un objeto:
|
||||
<blockquote>var myObj = {<br> prop1: "val1",<br> prop2: "val2"<br>};<br>var prop1val = myObj.prop1; // val1<br>var prop2val = myObj.prop2; // val2</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Lea los valores de propiedad de <code>testObj</code> usando la notación de puntos. Establezca la variable <code>hatValue</code> igual al <code>hat</code> propiedad del objeto y establezca la variable <code>shirtValue</code> igual a la <code>shirt</code> propiedad del objeto.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>hatValue</code> debe ser una cadena
|
||||
testString: 'assert(typeof hatValue === "string" , "<code>hatValue</code> should be a string");'
|
||||
- text: El valor de <code>hatValue</code> debe ser <code>"ballcap"</code>
|
||||
testString: 'assert(hatValue === "ballcap" , "The value of <code>hatValue</code> should be <code>"ballcap"</code>");'
|
||||
- text: <code>shirtValue</code> debe ser una cadena
|
||||
testString: 'assert(typeof shirtValue === "string" , "<code>shirtValue</code> should be a string");'
|
||||
- text: El valor de <code>shirtValue</code> debe ser <code>"jersey"</code>
|
||||
testString: 'assert(shirtValue === "jersey" , "The value of <code>shirtValue</code> should be <code>"jersey"</code>");'
|
||||
- text: Deberías usar la notación de puntos dos veces.
|
||||
testString: 'assert(code.match(/testObj\.\w+/g).length > 1, "You should use dot notation twice");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var hatValue = testObj; // Change this line
|
||||
var shirtValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
var hatValue = testObj.hat;
|
||||
var shirtValue = testObj.shirt;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c9
|
||||
title: Accessing Object Properties with Variables
|
||||
localeTitle: Accediendo a las propiedades del objeto con variables
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/accessing-objects-properties-with-variables'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Otro uso de la notación de corchetes en los objetos es acceder a una propiedad que se almacena como el valor de una variable. Esto puede ser muy útil para iterar a través de las propiedades de un objeto o al acceder a una tabla de búsqueda.
|
||||
Aquí hay un ejemplo del uso de una variable para acceder a una propiedad:
|
||||
<blockquote>var dogs = {<br> Fido: "Mutt",
|
||||
Hunter: "Doberman",
|
||||
Snoopie: "Beagle"<br>};<br>var myDog = "Hunter";<br>var myBreed = dogs[myDog];<br>console.log(myBreed); // "Doberman"</blockquote>
|
||||
Otra forma en que puede usar este concepto es cuando el nombre de la propiedad se recopila dinámicamente durante la ejecución del programa, de la siguiente manera:
|
||||
<blockquote>var someObj = {<br> propName: "John"<br>};<br>function propPrefix(str) {<br> var s = "prop";<br> return s + str;<br>}<br>var someProp = propPrefix("Name"); // someProp now holds the value 'propName'<br>console.log(someObj[someProp]); // "John"</blockquote>
|
||||
Tenga en cuenta que <em>no</em> usamos comillas alrededor del nombre de la variable cuando la usamos para acceder a la propiedad porque estamos usando el <em>valor</em> de la variable, no el <em>nombre</em> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use la variable <code>playerNumber</code> para buscar el jugador <code>16</code> en <code>testObj</code> usando la notación de corchete. Luego asigna ese nombre a la variable del <code>player</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>playerNumber</code> debería ser un número
|
||||
testString: 'assert(typeof playerNumber === "number", "<code>playerNumber</code> should be a number");'
|
||||
- text: El <code>player</code> variable debe ser una cadena.
|
||||
testString: 'assert(typeof player === "string", "The variable <code>player</code> should be a string");'
|
||||
- text: El valor del <code>player</code> debe ser "Montana".
|
||||
testString: 'assert(player === "Montana", "The value of <code>player</code> should be "Montana"");'
|
||||
- text: Debe usar la notación de corchetes para acceder a <code>testObj</code>
|
||||
testString: 'assert(/testObj\s*?\[.*?\]/.test(code),"You should use bracket notation to access <code>testObj</code>");'
|
||||
- text: No debes asignar el valor <code>Montana</code> al <code>player</code> variable directamente.
|
||||
testString: 'assert(!code.match(/player\s*=\s*"|\"\s*Montana\s*"|\"\s*;/gi),"You should not assign the value <code>Montana</code> to the variable <code>player</code> directly.");'
|
||||
- text: Debería usar la variable <code>playerNumber</code> en su notación de corchete
|
||||
testString: 'assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code),"You should be using the variable <code>playerNumber</code> in your bracket notation");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
|
||||
// Only change code below this line;
|
||||
|
||||
var playerNumber; // Change this Line
|
||||
var player = testObj; // Change this Line
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
var playerNumber = 16;
|
||||
var player = testObj[playerNumber];
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d2
|
||||
title: Add New Properties to a JavaScript Object
|
||||
localeTitle: Agregar nuevas propiedades a un objeto de JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Puede agregar nuevas propiedades a los objetos JavaScript existentes de la misma manera que los modificaría.
|
||||
Así es como agregaríamos una propiedad de <code>"bark"</code> a <code>ourDog</code> :
|
||||
<code>ourDog.bark = "bow-wow";</code>
|
||||
o
|
||||
<code>ourDog["bark"] = "bow-wow";</code>
|
||||
Ahora, cuando evaluamos <code>ourDog.bark</code> , obtendremos su ladrido, "bow-wow".
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agrega una propiedad de <code>"bark"</code> a <code>myDog</code> y <code>myDog</code> con un sonido de perro, como "woof". Puede usar la notación de punto o corchete.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Agregue la propiedad <code>"bark"</code> a <code>myDog</code> .
|
||||
testString: 'assert(myDog.bark !== undefined, "Add the property <code>"bark"</code> to <code>myDog</code>.");'
|
||||
- text: No agregue <code>"bark"</code> a la sección de configuración
|
||||
testString: 'assert(!/bark[^\n]:/.test(code), "Do not add <code>"bark"</code> to the setup section");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
|
||||
ourDog.bark = "bow-wow";
|
||||
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
myDog.bark = "Woof Woof";
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,68 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb3bdef
|
||||
title: Add Two Numbers with JavaScript
|
||||
localeTitle: Añadir dos números con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<code>Number</code> es un tipo de datos en JavaScript que representa datos numéricos.
|
||||
Ahora vamos a tratar de sumar dos números usando JavaScript.
|
||||
JavaScript usa el símbolo <code>+</code> como operación de suma cuando se coloca entre dos números.
|
||||
<strong>Ejemplo</strong>
|
||||
<blockquote>myVar = 5 + 10; // assigned 15</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambia el <code>0</code> para que la suma sea igual a <code>20</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>sum</code> debe ser igual a <code>20</code>
|
||||
testString: 'assert(sum === 20, "<code>sum</code> should equal <code>20</code>");'
|
||||
- text: Usa el operador <code>+</code>
|
||||
testString: 'assert(/\+/.test(code), "Use the <code>+</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var sum = 10 + 0;
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var sum = 10 + 10;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244de
|
||||
title: Adding a Default Option in Switch Statements
|
||||
localeTitle: Adición de una opción predeterminada en los estados de cambio
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/adding-a-default-option-in-switch-statements'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En una declaración de <code>switch</code> , es posible que no pueda especificar todos los valores posibles como declaraciones de <code>case</code> . En su lugar, puede agregar la declaración <code>default</code> que se ejecutará si no se encuentran declaraciones de <code>case</code> coincidentes. Piense en ello como la última instrucción <code>else</code> en una cadena <code>if/else</code> .
|
||||
Una declaración por <code>default</code> debe ser el último caso.
|
||||
<blockquote>switch (num) {<br> case value1:<br> statement1;<br> break;<br> case value2:<br> statement2;<br> break;<br>...<br> default:<br> defaultStatement;<br> break;<br>}</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Escriba una instrucción de cambio para establecer la <code>answer</code> para las siguientes condiciones: <br> <code>"a"</code> - "manzana" <br> <code>"b"</code> - "pájaro" <br> <code>"c"</code> - "gato" <br> <code>default</code> - "cosas"
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>switchOfStuff("a")</code> debe tener un valor de "apple"
|
||||
testString: 'assert(switchOfStuff("a") === "apple", "<code>switchOfStuff("a")</code> should have a value of "apple"");'
|
||||
- text: <code>switchOfStuff("b")</code> debe tener un valor de "bird"
|
||||
testString: 'assert(switchOfStuff("b") === "bird", "<code>switchOfStuff("b")</code> should have a value of "bird"");'
|
||||
- text: <code>switchOfStuff("c")</code> debe tener un valor de "cat"
|
||||
testString: 'assert(switchOfStuff("c") === "cat", "<code>switchOfStuff("c")</code> should have a value of "cat"");'
|
||||
- text: <code>switchOfStuff("d")</code> debe tener un valor de "cosas"
|
||||
testString: 'assert(switchOfStuff("d") === "stuff", "<code>switchOfStuff("d")</code> should have a value of "stuff"");'
|
||||
- text: <code>switchOfStuff(4)</code> debe tener un valor de "cosas"
|
||||
testString: 'assert(switchOfStuff(4) === "stuff", "<code>switchOfStuff(4)</code> should have a value of "stuff"");'
|
||||
- text: No debes usar ninguna declaración <code>if</code> o <code>else</code>
|
||||
testString: 'assert(!/else/g.test(code) || !/if/g.test(code), "You should not use any <code>if</code> or <code>else</code> statements");'
|
||||
- text: Debes usar una declaración por <code>default</code>
|
||||
testString: 'assert(switchOfStuff("string-to-trigger-default-case") === "stuff", "You should use a <code>default</code> statement");'
|
||||
- text: Debe tener al menos 3 declaraciones de <code>break</code>
|
||||
testString: 'assert(code.match(/break/g).length > 2, "You should have at least 3 <code>break</code> statements");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
switchOfStuff(1);
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case "a":
|
||||
answer = "apple";
|
||||
break;
|
||||
case "b":
|
||||
answer = "bird";
|
||||
break;
|
||||
case "c":
|
||||
answer = "cat";
|
||||
break;
|
||||
default:
|
||||
answer = "stuff";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ed
|
||||
title: Appending Variables to Strings
|
||||
localeTitle: Anexando Variables a las Cadenas
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/appending-variables-to-strings'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Al igual que podemos construir una cadena sobre varias líneas a partir de <dfn>literales</dfn> de cadena, también podemos agregar variables a una cadena usando el operador más es igual a ( <code>+=</code> ).
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Establezca <code>someAdjective</code> y <code>someAdjective</code> a <code>myStr</code> usando el operador <code>+=</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>someAdjective</code> debe establecerse en una cadena de al menos 3 caracteres de largo
|
||||
testString: 'assert(typeof someAdjective !== "undefined" && someAdjective.length > 2, "<code>someAdjective</code> should be set to a string at least 3 characters long");'
|
||||
- text: <code>someAdjective</code> de <code>someAdjective</code> a <code>myStr</code> usando el operador <code>+=</code>
|
||||
testString: 'assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0, "Append <code>someAdjective</code> to <code>myStr</code> using the <code>+=</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var anAdjective = "awesome!";
|
||||
var ourStr = "freeCodeCamp is ";
|
||||
ourStr += anAdjective;
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var someAdjective;
|
||||
var myStr = "Learning to code is ";
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var anAdjective = "awesome!";
|
||||
var ourStr = "freeCodeCamp is ";
|
||||
ourStr += anAdjective;
|
||||
|
||||
var someAdjective = "neat";
|
||||
var myStr = "Learning to code is ";
|
||||
myStr += someAdjective;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c3
|
||||
title: Assignment with a Returned Value
|
||||
localeTitle: Asignación con un valor devuelto
|
||||
challengeType: 1
|
||||
guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/assignment-with-a-returned-value'
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Si recordará de nuestra discusión sobre el <a href="javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">almacenamiento de valores con el operador de asignación</a> , todo a la derecha del signo igual se resuelve antes de que se asigne el valor. Esto significa que podemos tomar el valor de retorno de una función y asignarlo a una variable.
|
||||
Supongamos que hemos predefinido una <code>sum</code> función que suma dos números, luego:
|
||||
<code>ourSum = sum(5, 12);</code>
|
||||
llamará a la función <code>sum</code> , que devuelve un valor de <code>17</code> y lo asigna a <code>ourSum</code> variable <code>ourSum</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Llame a la función <code>processArg</code> con un argumento de <code>7</code> y asigne su valor de retorno a la variable <code>processed</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>processed</code> debe tener un valor de <code>2</code>
|
||||
testString: 'assert(processed === 2, "<code>processed</code> should have a value of <code>2</code>");'
|
||||
- text: Debes asignar <code>processArg</code> a <code>processed</code>
|
||||
testString: 'assert(/processed\s*=\s*processArg\(\s*7\s*\)\s*;/.test(code), "You should assign <code>processArg</code> to <code>processed</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var changed = 0;
|
||||
|
||||
function change(num) {
|
||||
return (num + 5) / 3;
|
||||
}
|
||||
|
||||
changed = change(10);
|
||||
|
||||
// Setup
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
processed = processArg(7);
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d0
|
||||
title: Build JavaScript Objects
|
||||
localeTitle: Construir objetos de JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Es posible que hayas escuchado el término <code>object</code> antes.
|
||||
objetos son similares a las <code>arrays</code> , excepto que en lugar de utilizar índices para acceder y modificar sus datos, puede acceder a los datos en objetos a través de lo que se denomina <code>properties</code> .
|
||||
objetos son útiles para almacenar datos de manera estructurada y pueden representar objetos del mundo real, como un gato.
|
||||
Aquí hay una muestra de un objeto de gato:
|
||||
<blockquote>var cat = {<br> "name": "Whiskers",<br> "legs": 4,<br> "tails": 1,<br> "enemies": ["Water", "Dogs"]<br>};</blockquote>
|
||||
En este ejemplo, todas las propiedades se almacenan como cadenas, como <code>"name"</code> , <code>"legs"</code> y <code>"tails"</code> . Sin embargo, también puede utilizar los números como propiedades. Incluso puede omitir las comillas para las propiedades de cadena de una sola palabra, de la siguiente manera:
|
||||
<blockquote>var anotherObject = {<br> make: "Ford",<br> 5: "five",<br> "model": "focus"<br>};</blockquote>
|
||||
Sin embargo, si su objeto tiene propiedades que no son de cadena, JavaScript las encasillará automáticamente como cadenas.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Haz un objeto que represente un perro llamado <code>myDog</code> que contenga las propiedades <code>"name"</code> (una cadena), <code>"legs"</code> , <code>"tails"</code> y <code>"friends"</code> .
|
||||
Puede establecer estas propiedades de objeto en los valores que desee, siempre que <code>"name"</code> sea una cadena, <code>"legs"</code> y <code>"tails"</code> sean números, y <code>"friends"</code> es una matriz.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myDog</code> debe contener el <code>name</code> la propiedad y debe ser una <code>string</code> .
|
||||
testString: 'assert((function(z){if(z.hasOwnProperty("name") && z.name !== undefined && typeof z.name === "string"){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>name</code> and it should be a <code>string</code>.");'
|
||||
- text: <code>myDog</code> debe contener las <code>legs</code> propiedad y debe ser un <code>number</code> .
|
||||
testString: 'assert((function(z){if(z.hasOwnProperty("legs") && z.legs !== undefined && typeof z.legs === "number"){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>legs</code> and it should be a <code>number</code>.");'
|
||||
- text: <code>myDog</code> debe contener las <code>tails</code> propiedad y debe ser un <code>number</code> .
|
||||
testString: 'assert((function(z){if(z.hasOwnProperty("tails") && z.tails !== undefined && typeof z.tails === "number"){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>tails</code> and it should be a <code>number</code>.");'
|
||||
- text: <code>myDog</code> debe contener los <code>friends</code> la propiedad y debe ser una <code>array</code> .
|
||||
testString: 'assert((function(z){if(z.hasOwnProperty("friends") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), "<code>myDog</code> should contain the property <code>friends</code> and it should be an <code>array</code>.");'
|
||||
- text: <code>myDog</code> solo debe contener todas las propiedades dadas.
|
||||
testString: 'assert((function(z){return Object.keys(z).length === 4;})(myDog), "<code>myDog</code> should only contain all the given properties.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
var myDog = {
|
||||
|
||||
|
||||
|
||||
|
||||
};
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,100 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dc
|
||||
title: Chaining If Else Statements
|
||||
localeTitle: Encadenamiento en caso contrario
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<code>if/else</code> sentencias pueden ser encadenadas juntas para lógica compleja. Aquí está el <dfn>pseudocódigo</dfn> de múltiples encadenadas <code>if</code> / <code>else if</code> enunciados:
|
||||
<blockquote>if ( <em>condition1</em> ) {<br> <em>statement1</em> <br>} else if ( <em>condition2</em> ) {<br> <em>statement2</em> <br>} else if ( <em>condition3</em> ) {<br> <em>statement3</em> <br>. . .<br>} else {<br> <em>statementN</em> <br>}</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Escribir en cadena <code>if</code> / <code>else if</code> sentencias para cumplir con las siguientes condiciones:
|
||||
<code>num < 5</code> - devolver "Tiny" <br> <code>num < 10</code> - devuelve "Small" <br> <code>num < 15</code> - devuelve "Medio" <br> <code>num < 20</code> - devuelve "Large" <br> <code>num >= 20</code> - devuelve "Enorme"
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Debes tener al menos cuatro declaraciones <code>else</code>
|
||||
testString: 'assert(code.match(/else/g).length > 3, "You should have at least four <code>else</code> statements");'
|
||||
- text: Debes tener al menos cuatro <code>if</code> declaraciones
|
||||
testString: 'assert(code.match(/if/g).length > 3, "You should have at least four <code>if</code> statements");'
|
||||
- text: Debe tener al menos una declaración de <code>return</code>
|
||||
testString: 'assert(code.match(/return/g).length >= 1, "You should have at least one <code>return</code> statement");'
|
||||
- text: <code>testSize(0)</code> debería devolver "Tiny"
|
||||
testString: 'assert(testSize(0) === "Tiny", "<code>testSize(0)</code> should return "Tiny"");'
|
||||
- text: <code>testSize(4)</code> debería devolver "Tiny"
|
||||
testString: 'assert(testSize(4) === "Tiny", "<code>testSize(4)</code> should return "Tiny"");'
|
||||
- text: <code>testSize(5)</code> debe devolver "Small"
|
||||
testString: 'assert(testSize(5) === "Small", "<code>testSize(5)</code> should return "Small"");'
|
||||
- text: <code>testSize(8)</code> debe devolver "Small"
|
||||
testString: 'assert(testSize(8) === "Small", "<code>testSize(8)</code> should return "Small"");'
|
||||
- text: <code>testSize(10)</code> debe devolver "Medium"
|
||||
testString: 'assert(testSize(10) === "Medium", "<code>testSize(10)</code> should return "Medium"");'
|
||||
- text: <code>testSize(14)</code> debe devolver "Medium"
|
||||
testString: 'assert(testSize(14) === "Medium", "<code>testSize(14)</code> should return "Medium"");'
|
||||
- text: <code>testSize(15)</code> debe devolver "Large"
|
||||
testString: 'assert(testSize(15) === "Large", "<code>testSize(15)</code> should return "Large"");'
|
||||
- text: <code>testSize(17)</code> debería devolver "Large"
|
||||
testString: 'assert(testSize(17) === "Large", "<code>testSize(17)</code> should return "Large"");'
|
||||
- text: <code>testSize(20)</code> debería devolver "Huge"
|
||||
testString: 'assert(testSize(20) === "Huge", "<code>testSize(20)</code> should return "Huge"");'
|
||||
- text: <code>testSize(25)</code> debería devolver "Huge"
|
||||
testString: 'assert(testSize(25) === "Huge", "<code>testSize(25)</code> should return "Huge"");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testSize(7);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
if (num < 5) {
|
||||
return "Tiny";
|
||||
} else if (num < 10) {
|
||||
return "Small";
|
||||
} else if (num < 15) {
|
||||
return "Medium";
|
||||
} else if (num < 20) {
|
||||
return "Large";
|
||||
} else {
|
||||
return "Huge";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,62 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb4bdef
|
||||
title: Comment Your JavaScript Code
|
||||
localeTitle: Comenta tu código JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
comentarios son líneas de código que JavaScript ignorará intencionalmente. Los comentarios son una excelente manera de dejar notas para usted y para otras personas que más tarde necesitarán averiguar qué hace ese código.
|
||||
Hay dos formas de escribir comentarios en JavaScript:
|
||||
Al usar <code>//</code> le indicará a JavaScript que ignore el resto del texto en la línea actual:
|
||||
<blockquote>// This is an in-line comment.</blockquote>
|
||||
Puede hacer un comentario de varias líneas comenzando con <code>/*</code> y terminando con <code>*/</code> :
|
||||
<blockquote>/* This is a<br>multi-line comment */</blockquote>
|
||||
<strong>Mejores Prácticas</strong> <br> A medida que escribe el código, debe agregar comentarios regularmente para aclarar la función de partes de su código. Los buenos comentarios pueden ayudar a comunicar la intención de su código, tanto para los demás <em>como</em> para su futuro.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Intenta crear uno de cada tipo de comentario.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Cree un <code>//</code> estilo de comentario que contenga al menos cinco letras.
|
||||
testString: 'assert(code.match(/(\/\/)...../g), "Create a <code>//</code> style comment that contains at least five letters.");'
|
||||
- text: Cree un comentario de estilo <code>/* */</code> que contenga al menos cinco letras.
|
||||
testString: 'assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm), "Create a <code>/* */</code> style comment that contains at least five letters.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
// Fake Comment
|
||||
/* Another Comment */
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d0
|
||||
title: Comparison with the Equality Operator
|
||||
localeTitle: Comparación con el operador de igualdad
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Hay muchos <dfn>operadores de comparación</dfn> en JavaScript. Todos estos operadores devuelven un valor <code>true</code> o <code>false</code> booleano.
|
||||
El operador más básico es el operador de igualdad <code>==</code> . El operador de igualdad compara dos valores y devuelve <code>true</code> si son equivalentes o <code>false</code> si no lo son. Tenga en cuenta que la igualdad es diferente de la asignación ( <code>=</code> ), que asigna el valor a la derecha del operador a una variable en la izquierda.
|
||||
<blockquote>function equalityTest(myVal) {<br> if (myVal == 10) {<br> return "Equal";<br> }<br> return "Not Equal";<br>}</blockquote>
|
||||
Si <code>myVal</code> es igual a <code>10</code> , el operador de igualdad devuelve <code>true</code> , por lo que se ejecutará el código entre llaves y la función devolverá <code>"Equal"</code> . De lo contrario, la función devolverá <code>"Not Equal"</code> .
|
||||
Para que JavaScript pueda comparar dos <code>data types</code> (por ejemplo, <code>numbers</code> y <code>strings</code> ), debe convertir un tipo a otro. Esto se conoce como "Tipo de coerción". Una vez que lo hace, sin embargo, puede comparar los términos de la siguiente manera:
|
||||
<blockquote>1 == 1 // true<br>1 == 2 // false<br>1 == '1' // true<br>"3" == 3 // true</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue el <code>equality operator</code> a la línea indicada para que la función devuelva "Igual" cuando <code>val</code> sea equivalente a <code>12</code>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testEqual(10)</code> debe devolver "No es igual"
|
||||
testString: 'assert(testEqual(10) === "Not Equal", "<code>testEqual(10)</code> should return "Not Equal"");'
|
||||
- text: <code>testEqual(12)</code> debe devolver "Igual"
|
||||
testString: 'assert(testEqual(12) === "Equal", "<code>testEqual(12)</code> should return "Equal"");'
|
||||
- text: <code>testEqual("12")</code> debe devolver "Equal"
|
||||
testString: 'assert(testEqual("12") === "Equal", "<code>testEqual("12")</code> should return "Equal"");'
|
||||
- text: Debes usar el operador <code>==</code>
|
||||
testString: 'assert(code.match(/==/g) && !code.match(/===/g), "You should use the <code>==</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testEqual(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testEqual(val) {
|
||||
if (val == 12) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d4
|
||||
title: Comparison with the Greater Than Operator
|
||||
localeTitle: Comparación con el operador mayor que
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador mayor que ( <code>></code> ) compara los valores de dos números. Si el número a la izquierda es mayor que el número a la derecha, devuelve <code>true</code> . De lo contrario, devuelve <code>false</code> .
|
||||
Al igual que el operador de igualdad, el operador mayor que el convertirá los tipos de datos de valores al comparar.
|
||||
<strong>ejemplos</strong>
|
||||
<blockquote> 5 > 3 // true<br> 7 > '3' // true<br> 2 > 3 // false<br>'1' > 9 // false</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue el operador <code>greater than</code> a las líneas indicadas para que las declaraciones de devolución tengan sentido.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testGreaterThan(0)</code> debe devolver "10 o inferior"
|
||||
testString: 'assert(testGreaterThan(0) === "10 or Under", "<code>testGreaterThan(0)</code> should return "10 or Under"");'
|
||||
- text: <code>testGreaterThan(10)</code> debe devolver "10 o inferior"
|
||||
testString: 'assert(testGreaterThan(10) === "10 or Under", "<code>testGreaterThan(10)</code> should return "10 or Under"");'
|
||||
- text: <code>testGreaterThan(11)</code> debe devolver "Over 10"
|
||||
testString: 'assert(testGreaterThan(11) === "Over 10", "<code>testGreaterThan(11)</code> should return "Over 10"");'
|
||||
- text: <code>testGreaterThan(99)</code> debe devolver "Over 10"
|
||||
testString: 'assert(testGreaterThan(99) === "Over 10", "<code>testGreaterThan(99)</code> should return "Over 10"");'
|
||||
- text: <code>testGreaterThan(100)</code> debe devolver "Over 10"
|
||||
testString: 'assert(testGreaterThan(100) === "Over 10", "<code>testGreaterThan(100)</code> should return "Over 10"");'
|
||||
- text: <code>testGreaterThan(101)</code> debe devolver "Over 100"
|
||||
testString: 'assert(testGreaterThan(101) === "Over 100", "<code>testGreaterThan(101)</code> should return "Over 100"");'
|
||||
- text: <code>testGreaterThan(150)</code> debe devolver "Over 100"
|
||||
testString: 'assert(testGreaterThan(150) === "Over 100", "<code>testGreaterThan(150)</code> should return "Over 100"");'
|
||||
- text: Debes usar el operador <code>></code> al menos dos veces
|
||||
testString: 'assert(code.match(/val\s*>\s*("|")*\d+("|")*/g).length > 1, "You should use the <code>></code> operator at least twice");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
|
||||
return "10 or Under";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testGreaterThan(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val > 100) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
if (val > 10) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
return "10 or Under";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d5
|
||||
title: Comparison with the Greater Than Or Equal To Operator
|
||||
localeTitle: Comparación con el operador mayor o igual que el operador
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador <code>greater than or equal to</code> ( <code>>=</code> ) compara los valores de dos números. Si el número a la izquierda es mayor o igual que el número a la derecha, devuelve <code>true</code> . De lo contrario, devuelve <code>false</code> .
|
||||
Al igual que el operador de igualdad, <code>greater than or equal to</code> operador convertirá los tipos de datos al comparar.
|
||||
<strong>ejemplos</strong>
|
||||
<blockquote> 6 >= 6 // true<br> 7 >= '3' // true<br> 2 >= 3 // false<br>'7' >= 9 // false</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue el operador <code>greater than or equal to</code> las líneas indicadas para que las declaraciones de devolución tengan sentido.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testGreaterOrEqual(0)</code> debe devolver "Menos de 10"
|
||||
testString: 'assert(testGreaterOrEqual(0) === "Less than 10", "<code>testGreaterOrEqual(0)</code> should return "Less than 10"");'
|
||||
- text: <code>testGreaterOrEqual(9)</code> debe devolver "Menos de 10"
|
||||
testString: 'assert(testGreaterOrEqual(9) === "Less than 10", "<code>testGreaterOrEqual(9)</code> should return "Less than 10"");'
|
||||
- text: <code>testGreaterOrEqual(10)</code> debe devolver "10 o más"
|
||||
testString: 'assert(testGreaterOrEqual(10) === "10 or Over", "<code>testGreaterOrEqual(10)</code> should return "10 or Over"");'
|
||||
- text: <code>testGreaterOrEqual(11)</code> debe devolver "10 o más"
|
||||
testString: 'assert(testGreaterOrEqual(11) === "10 or Over", "<code>testGreaterOrEqual(11)</code> should return "10 or Over"");'
|
||||
- text: <code>testGreaterOrEqual(19)</code> debe devolver "10 o más"
|
||||
testString: 'assert(testGreaterOrEqual(19) === "10 or Over", "<code>testGreaterOrEqual(19)</code> should return "10 or Over"");'
|
||||
- text: <code>testGreaterOrEqual(100)</code> debe devolver "20 o más"
|
||||
testString: 'assert(testGreaterOrEqual(100) === "20 or Over", "<code>testGreaterOrEqual(100)</code> should return "20 or Over"");'
|
||||
- text: <code>testGreaterOrEqual(21)</code> debe devolver "20 o más"
|
||||
testString: 'assert(testGreaterOrEqual(21) === "20 or Over", "<code>testGreaterOrEqual(21)</code> should return "20 or Over"");'
|
||||
- text: Debe usar el operador <code>>=</code> al menos dos veces
|
||||
testString: 'assert(code.match(/val\s*>=\s*("|")*\d+("|")*/g).length > 1, "You should use the <code>>=</code> operator at least twice");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testGreaterOrEqual(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val >= 20) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val >= 10) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d2
|
||||
title: Comparison with the Inequality Operator
|
||||
localeTitle: Comparación con el operador de desigualdad
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador de desigualdad ( <code>!=</code> ) Es el opuesto del operador de igualdad. Significa "No es igual" y devuelve <code>false</code> donde la igualdad se volvería <code>true</code> y <em>viceversa</em> . Al igual que el operador de igualdad, el operador de desigualdad convertirá los tipos de datos de los valores al comparar.
|
||||
<strong>ejemplos</strong>
|
||||
<blockquote>1 != 2 // true<br>1 != "1" // false<br>1 != '1' // false<br>1 != true // false<br>0 != false // false</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue el operador de desigualdad <code>!=</code> En la instrucción <code>if</code> para que la función devuelva "No igual" cuando <code>val</code> no es equivalente a <code>99</code>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testNotEqual(99)</code> debe devolver "Igual"
|
||||
testString: 'assert(testNotEqual(99) === "Equal", "<code>testNotEqual(99)</code> should return "Equal"");'
|
||||
- text: <code>testNotEqual("99")</code> debe devolver "Equal"
|
||||
testString: 'assert(testNotEqual("99") === "Equal", "<code>testNotEqual("99")</code> should return "Equal"");'
|
||||
- text: <code>testNotEqual(12)</code> debe devolver "No es igual"
|
||||
testString: 'assert(testNotEqual(12) === "Not Equal", "<code>testNotEqual(12)</code> should return "Not Equal"");'
|
||||
- text: <code>testNotEqual("12")</code> debe devolver "Not Equal"
|
||||
testString: 'assert(testNotEqual("12") === "Not Equal", "<code>testNotEqual("12")</code> should return "Not Equal"");'
|
||||
- text: <code>testNotEqual("bob")</code> debe devolver "Not Equal"
|
||||
testString: 'assert(testNotEqual("bob") === "Not Equal", "<code>testNotEqual("bob")</code> should return "Not Equal"");'
|
||||
- text: Debes usar el operador <code>!=</code>
|
||||
testString: 'assert(code.match(/(?!!==)!=/), "You should use the <code>!=</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testNotEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testNotEqual(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testNotEqual(val) {
|
||||
if (val != 99) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d6
|
||||
title: Comparison with the Less Than Operator
|
||||
localeTitle: Comparación con el operador menor que
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador <dfn>menor que</dfn> ( <code><</code> ) compara los valores de dos números. Si el número a la izquierda es menor que el número a la derecha, devuelve <code>true</code> . De lo contrario, devuelve <code>false</code> . Al igual que el operador de igualdad, <dfn>menos que el</dfn> operador convierte los tipos de datos al comparar.
|
||||
<strong>ejemplos</strong>
|
||||
<blockquote>2 < 5 // true<br>'3' < 7 // true<br>5 < 5 // false<br>3 < 2 // false<br>'8' < 4 // false</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue el operador <code>less than</code> a las líneas indicadas para que las declaraciones de devolución tengan sentido.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testLessThan(0)</code> debe devolver "Under 25"
|
||||
testString: 'assert(testLessThan(0) === "Under 25", "<code>testLessThan(0)</code> should return "Under 25"");'
|
||||
- text: <code>testLessThan(24)</code> debe devolver "Under 25"
|
||||
testString: 'assert(testLessThan(24) === "Under 25", "<code>testLessThan(24)</code> should return "Under 25"");'
|
||||
- text: <code>testLessThan(25)</code> debe devolver "Under 55"
|
||||
testString: 'assert(testLessThan(25) === "Under 55", "<code>testLessThan(25)</code> should return "Under 55"");'
|
||||
- text: <code>testLessThan(54)</code> debe devolver "Under 55"
|
||||
testString: 'assert(testLessThan(54) === "Under 55", "<code>testLessThan(54)</code> should return "Under 55"");'
|
||||
- text: <code>testLessThan(55)</code> debería devolver "55 o más"
|
||||
testString: 'assert(testLessThan(55) === "55 or Over", "<code>testLessThan(55)</code> should return "55 or Over"");'
|
||||
- text: <code>testLessThan(99)</code> debería devolver "55 o más"
|
||||
testString: 'assert(testLessThan(99) === "55 or Over", "<code>testLessThan(99)</code> should return "55 or Over"");'
|
||||
- text: Debes usar el operador <code><</code> al menos dos veces
|
||||
testString: 'assert(code.match(/val\s*<\s*("|")*\d+("|")*/g).length > 1, "You should use the <code><</code> operator at least twice");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testLessThan(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val < 25) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val < 55) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d7
|
||||
title: Comparison with the Less Than Or Equal To Operator
|
||||
localeTitle: Comparación con el operador menor o igual que
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador <code>less than or equal to</code> ( <code><=</code> ) compara los valores de dos números. Si el número a la izquierda es menor o igual que el número a la derecha, devuelve <code>true</code> . Si el número de la izquierda es mayor que el de la derecha, devuelve <code>false</code> . Al igual que el operador de igualdad, <code>less than or equal to</code> convierte los tipos de datos.
|
||||
<strong>ejemplos</strong>
|
||||
<blockquote>4 <= 5 // true<br>'7' <= 7 // true<br>5 <= 5 // true<br>3 <= 2 // false<br>'8' <= 4 // false</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue el operador <code>less than or equal to</code> las líneas indicadas para que las declaraciones de devolución tengan sentido.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testLessOrEqual(0)</code> debe devolver "Más pequeño o igual a 12"
|
||||
testString: 'assert(testLessOrEqual(0) === "Smaller Than or Equal to 12", "<code>testLessOrEqual(0)</code> should return "Smaller Than or Equal to 12"");'
|
||||
- text: <code>testLessOrEqual(11)</code> debe devolver "Más pequeño o igual a 12"
|
||||
testString: 'assert(testLessOrEqual(11) === "Smaller Than or Equal to 12", "<code>testLessOrEqual(11)</code> should return "Smaller Than or Equal to 12"");'
|
||||
- text: <code>testLessOrEqual(12)</code> debe devolver "Más pequeño o igual a 12"
|
||||
testString: 'assert(testLessOrEqual(12) === "Smaller Than or Equal to 12", "<code>testLessOrEqual(12)</code> should return "Smaller Than or Equal to 12"");'
|
||||
- text: <code>testLessOrEqual(23)</code> debe devolver "Más pequeño o igual a 24"
|
||||
testString: 'assert(testLessOrEqual(23) === "Smaller Than or Equal to 24", "<code>testLessOrEqual(23)</code> should return "Smaller Than or Equal to 24"");'
|
||||
- text: <code>testLessOrEqual(24)</code> debe devolver "Más pequeño o igual a 24"
|
||||
testString: 'assert(testLessOrEqual(24) === "Smaller Than or Equal to 24", "<code>testLessOrEqual(24)</code> should return "Smaller Than or Equal to 24"");'
|
||||
- text: <code>testLessOrEqual(25)</code> debe devolver "Más de 24"
|
||||
testString: 'assert(testLessOrEqual(25) === "More Than 24", "<code>testLessOrEqual(25)</code> should return "More Than 24"");'
|
||||
- text: <code>testLessOrEqual(55)</code> debe devolver "Más de 24"
|
||||
testString: 'assert(testLessOrEqual(55) === "More Than 24", "<code>testLessOrEqual(55)</code> should return "More Than 24"");'
|
||||
- text: Debe usar el operador <code><=</code> al menos dos veces
|
||||
testString: 'assert(code.match(/val\s*<=\s*("|")*\d+("|")*/g).length > 1, "You should use the <code><=</code> operator at least twice");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testLessOrEqual(10);
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val <= 12) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val <= 24) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d1
|
||||
title: Comparison with the Strict Equality Operator
|
||||
localeTitle: Comparación con el operador de igualdad estricta
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Igualdad estricta ( <code>===</code> ) es la contraparte del operador de igualdad ( <code>==</code> ). Sin embargo, a diferencia del operador de igualdad, que intenta convertir ambos valores en comparación con un tipo común, el operador de igualdad estricta no realiza una conversión de tipo.
|
||||
Si los valores que se comparan tienen tipos diferentes, se consideran desiguales y el operador de igualdad estricta devolverá el valor falso.
|
||||
<strong>ejemplos</strong>
|
||||
<blockquote>3 === 3 // true<br>3 === '3' // false</blockquote>
|
||||
En el segundo ejemplo, <code>3</code> es un tipo de <code>Number</code> y <code>'3'</code> es un tipo de <code>String</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use el operador de igualdad estricta en la instrucción <code>if</code> para que la función devuelva "Igual" cuando <code>val</code> sea estrictamente igual a <code>7</code>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testStrict(10)</code> debe devolver "No es igual"
|
||||
testString: 'assert(testStrict(10) === "Not Equal", "<code>testStrict(10)</code> should return "Not Equal"");'
|
||||
- text: <code>testStrict(7)</code> debe devolver "Igual"
|
||||
testString: 'assert(testStrict(7) === "Equal", "<code>testStrict(7)</code> should return "Equal"");'
|
||||
- text: <code>testStrict("7")</code> debe devolver "Not Equal"
|
||||
testString: 'assert(testStrict("7") === "Not Equal", "<code>testStrict("7")</code> should return "Not Equal"");'
|
||||
- text: Debes usar el operador <code>===</code>
|
||||
testString: 'assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0, "You should use the <code>===</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrict(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testStrict(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testStrict(val) {
|
||||
if (val === 7) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d3
|
||||
title: Comparison with the Strict Inequality Operator
|
||||
localeTitle: Comparación con el operador de desigualdad estricta
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador de desigualdad estricta ( <code>!==</code> ) es el opuesto lógico del operador de igualdad estricta. Significa "Estrictamente no es igual" y devuelve <code>false</code> donde la igualdad estricta sería <code>true</code> y <em>viceversa</em> . La desigualdad estricta no convertirá los tipos de datos.
|
||||
<strong>ejemplos</strong>
|
||||
<blockquote>3 !== 3 // false<br>3 !== '3' // true<br>4 !== 3 // true</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue el <code>strict inequality operator</code> a la sentencia <code>if</code> para que la función devuelva "No igual" cuando <code>val</code> no sea estrictamente igual a <code>17</code>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>testStrictNotEqual(17)</code> debe devolver "Equal"
|
||||
testString: 'assert(testStrictNotEqual(17) === "Equal", "<code>testStrictNotEqual(17)</code> should return "Equal"");'
|
||||
- text: <code>testStrictNotEqual("17")</code> debe devolver "Not Equal"
|
||||
testString: 'assert(testStrictNotEqual("17") === "Not Equal", "<code>testStrictNotEqual("17")</code> should return "Not Equal"");'
|
||||
- text: <code>testStrictNotEqual(12)</code> debe devolver "Not Equal"
|
||||
testString: 'assert(testStrictNotEqual(12) === "Not Equal", "<code>testStrictNotEqual(12)</code> should return "Not Equal"");'
|
||||
- text: <code>testStrictNotEqual("bob")</code> debe devolver "Not Equal"
|
||||
testString: 'assert(testStrictNotEqual("bob") === "Not Equal", "<code>testStrictNotEqual("bob")</code> should return "Not Equal"");'
|
||||
- text: Debes usar el operador <code>!==</code>
|
||||
testString: 'assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0, "You should use the <code>!==</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrictNotEqual(val) {
|
||||
// Only Change Code Below this Line
|
||||
|
||||
if (val) {
|
||||
|
||||
// Only Change Code Above this Line
|
||||
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testStrictNotEqual(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testStrictNotEqual(val) {
|
||||
if (val !== 17) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,94 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d8
|
||||
title: Comparisons with the Logical And Operator
|
||||
localeTitle: Comparaciones con lo lógico y el operador.
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
A veces necesitará probar más de una cosa a la vez. La <dfn>lógica y el</dfn> operador ( <code>&&</code> ) devuelven <code>true</code> si y solo si los <dfn>operandos</dfn> a su izquierda y derecha son verdaderos.
|
||||
El mismo efecto podría lograrse anidando una instrucción if dentro de otra if:
|
||||
<blockquote>if (num > 5) {<br> if (num < 10) {<br> return "Yes";<br> }<br>}<br>return "No";</blockquote>
|
||||
solo devolverá "Sí" si <code>num</code> es mayor que <code>5</code> y menor que <code>10</code> . La misma lógica se puede escribir como:
|
||||
<blockquote>if (num > 5 && num < 10) {<br> return "Yes";<br>}<br>return "No";</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Combine las dos declaraciones if en una declaración que devolverá <code>"Yes"</code> si <code>val</code> es menor o igual a <code>50</code> y mayor o igual a <code>25</code> . De lo contrario, devolverá <code>"No"</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Debe usar el operador <code>&&</code> una vez
|
||||
testString: 'assert(code.match(/&&/g).length === 1, "You should use the <code>&&</code> operator once");'
|
||||
- text: Sólo debe tener una declaración <code>if</code>
|
||||
testString: 'assert(code.match(/if/g).length === 1, "You should only have one <code>if</code> statement");'
|
||||
- text: <code>testLogicalAnd(0)</code> debe devolver "No"
|
||||
testString: 'assert(testLogicalAnd(0) === "No", "<code>testLogicalAnd(0)</code> should return "No"");'
|
||||
- text: <code>testLogicalAnd(24)</code> debe devolver "No"
|
||||
testString: 'assert(testLogicalAnd(24) === "No", "<code>testLogicalAnd(24)</code> should return "No"");'
|
||||
- text: <code>testLogicalAnd(25)</code> debe devolver "Sí"
|
||||
testString: 'assert(testLogicalAnd(25) === "Yes", "<code>testLogicalAnd(25)</code> should return "Yes"");'
|
||||
- text: <code>testLogicalAnd(30)</code> debe devolver "Sí"
|
||||
testString: 'assert(testLogicalAnd(30) === "Yes", "<code>testLogicalAnd(30)</code> should return "Yes"");'
|
||||
- text: <code>testLogicalAnd(50)</code> debe devolver "Sí"
|
||||
testString: 'assert(testLogicalAnd(50) === "Yes", "<code>testLogicalAnd(50)</code> should return "Yes"");'
|
||||
- text: <code>testLogicalAnd(51)</code> debe devolver "No"
|
||||
testString: 'assert(testLogicalAnd(51) === "No", "<code>testLogicalAnd(51)</code> should return "No"");'
|
||||
- text: <code>testLogicalAnd(75)</code> debe devolver "No"
|
||||
testString: 'assert(testLogicalAnd(75) === "No", "<code>testLogicalAnd(75)</code> should return "No"");'
|
||||
- text: <code>testLogicalAnd(80)</code> debe devolver "No"
|
||||
testString: 'assert(testLogicalAnd(80) === "No", "<code>testLogicalAnd(80)</code> should return "No"");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
if (val) {
|
||||
return "Yes";
|
||||
}
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "No";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testLogicalAnd(10);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
if (val >= 25 && val <= 50) {
|
||||
return "Yes";
|
||||
}
|
||||
return "No";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d9
|
||||
title: Comparisons with the Logical Or Operator
|
||||
localeTitle: Comparaciones con el operador lógico o
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El <dfn>lógico u</dfn> operador ( <code>||</code> ) devuelve <code>true</code> si cualquiera de los <dfn>operandos</dfn> es <code>true</code> . De lo contrario, devuelve <code>false</code> .
|
||||
El operador <dfn>lógico</dfn> está compuesto de dos símbolos de tubería ( <code>|</code> ). Normalmente, esto se puede encontrar entre las teclas Retroceso e Intro.
|
||||
El patrón a continuación debe parecer familiar de los puntos de paso anteriores:
|
||||
<blockquote>if (num > 10) {<br> return "No";<br>}<br>if (num < 5) {<br> return "No";<br>}<br>return "Yes";</blockquote>
|
||||
devolverá "Sí" solo si el <code>num</code> está entre <code>5</code> y <code>10</code> (5 y 10 incluidos). La misma lógica se puede escribir como:
|
||||
<blockquote>if (num > 10 || num < 5) {<br> return "No";<br>}<br>return "Yes";</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Combine las dos declaraciones <code>if</code> en una declaración que devuelva <code>"Outside"</code> si <code>val</code> no está entre <code>10</code> y <code>20</code> , inclusive. De lo contrario, devuelve <code>"Inside"</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Deberías usar el <code>||</code> operador una vez
|
||||
testString: 'assert(code.match(/\|\|/g).length === 1, "You should use the <code>||</code> operator once");'
|
||||
- text: Sólo debe tener una declaración <code>if</code>
|
||||
testString: 'assert(code.match(/if/g).length === 1, "You should only have one <code>if</code> statement");'
|
||||
- text: <code>testLogicalOr(0)</code> debe devolver "Outside"
|
||||
testString: 'assert(testLogicalOr(0) === "Outside", "<code>testLogicalOr(0)</code> should return "Outside"");'
|
||||
- text: <code>testLogicalOr(9)</code> debe devolver "Outside"
|
||||
testString: 'assert(testLogicalOr(9) === "Outside", "<code>testLogicalOr(9)</code> should return "Outside"");'
|
||||
- text: <code>testLogicalOr(10)</code> debe devolver "Inside"
|
||||
testString: 'assert(testLogicalOr(10) === "Inside", "<code>testLogicalOr(10)</code> should return "Inside"");'
|
||||
- text: <code>testLogicalOr(15)</code> debe devolver "Inside"
|
||||
testString: 'assert(testLogicalOr(15) === "Inside", "<code>testLogicalOr(15)</code> should return "Inside"");'
|
||||
- text: <code>testLogicalOr(19)</code> debe devolver "Inside"
|
||||
testString: 'assert(testLogicalOr(19) === "Inside", "<code>testLogicalOr(19)</code> should return "Inside"");'
|
||||
- text: <code>testLogicalOr(20)</code> debe devolver "Inside"
|
||||
testString: 'assert(testLogicalOr(20) === "Inside", "<code>testLogicalOr(20)</code> should return "Inside"");'
|
||||
- text: <code>testLogicalOr(21)</code> debe devolver "Outside"
|
||||
testString: 'assert(testLogicalOr(21) === "Outside", "<code>testLogicalOr(21)</code> should return "Outside"");'
|
||||
- text: <code>testLogicalOr(25)</code> debe devolver "Outside"
|
||||
testString: 'assert(testLogicalOr(25) === "Outside", "<code>testLogicalOr(25)</code> should return "Outside"");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "Inside";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testLogicalOr(15);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
if (val < 10 || val > 20) {
|
||||
return "Outside";
|
||||
}
|
||||
return "Inside";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244af
|
||||
title: Compound Assignment With Augmented Addition
|
||||
localeTitle: Asignación compuesta con adición aumentada
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En la programación, es común usar asignaciones para modificar el contenido de una variable. Recuerde que todo a la derecha del signo igual se evalúa primero, por lo que podemos decir:
|
||||
<code>myVar = myVar + 5;</code>
|
||||
para agregar <code>5</code> a <code>myVar</code> . Dado que este es un patrón tan común, hay operadores que realizan tanto una operación matemática como una asignación en un solo paso.
|
||||
Uno de tales operadores es el operador <code>+=</code> .
|
||||
<blockquote>var myVar = 1;<br>myVar += 5;<br>console.log(myVar); // Returns 6</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Convierta las asignaciones para <code>a</code> , <code>b</code> y <code>c</code> para usar el operador <code>+=</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>a</code> debe ser igual a <code>15</code>
|
||||
testString: 'assert(a === 15, "<code>a</code> should equal <code>15</code>");'
|
||||
- text: <code>b</code> debe ser igual a <code>26</code>
|
||||
testString: 'assert(b === 26, "<code>b</code> should equal <code>26</code>");'
|
||||
- text: <code>c</code> debería ser igual a <code>19</code>
|
||||
testString: 'assert(c === 19, "<code>c</code> should equal <code>19</code>");'
|
||||
- text: Debes usar el operador <code>+=</code> para cada variable
|
||||
testString: 'assert(code.match(/\+=/g).length === 3, "You should use the <code>+=</code> operator for each variable");'
|
||||
- text: No modifique el código sobre la línea.
|
||||
testString: 'assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code), "Do not modify the code above the line");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
// Only modify code below this line
|
||||
|
||||
a = a + 12;
|
||||
b = 9 + b;
|
||||
c = c + 7;
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
a += 12;
|
||||
b += 9;
|
||||
c += 7;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b2
|
||||
title: Compound Assignment With Augmented Division
|
||||
localeTitle: Asignación compuesta con división aumentada
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador <code>/=</code> divide una variable por otro número.
|
||||
<code>myVar = myVar / 5;</code>
|
||||
<code>myVar</code> por <code>5</code> . Esto se puede reescribir como:
|
||||
<code>myVar /= 5;</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Convierta las asignaciones para <code>a</code> , <code>b</code> y <code>c</code> para usar el operador <code>/=</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>a</code> debería ser igual a <code>4</code>
|
||||
testString: 'assert(a === 4, "<code>a</code> should equal <code>4</code>");'
|
||||
- text: <code>b</code> debería ser igual a <code>27</code>
|
||||
testString: 'assert(b === 27, "<code>b</code> should equal <code>27</code>");'
|
||||
- text: <code>c</code> debería ser igual a <code>3</code>
|
||||
testString: 'assert(c === 3, "<code>c</code> should equal <code>3</code>");'
|
||||
- text: Debes usar el operador <code>/=</code> para cada variable
|
||||
testString: 'assert(code.match(/\/=/g).length === 3, "You should use the <code>/=</code> operator for each variable");'
|
||||
- text: No modifique el código sobre la línea.
|
||||
testString: 'assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code), "Do not modify the code above the line");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
// Only modify code below this line
|
||||
|
||||
a = a / 12;
|
||||
b = b / 4;
|
||||
c = c / 11;
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
a /= 12;
|
||||
b /= 4;
|
||||
c /= 11;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b1
|
||||
title: Compound Assignment With Augmented Multiplication
|
||||
localeTitle: Asignación compuesta con multiplicación aumentada
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador <code>*=</code> multiplica una variable por un número.
|
||||
<code>myVar = myVar * 5;</code>
|
||||
multiplicará <code>myVar</code> por <code>5</code> . Esto se puede reescribir como:
|
||||
<code>myVar *= 5;</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Convierta las asignaciones para <code>a</code> , <code>b</code> y <code>c</code> para usar el operador <code>*=</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>a</code> debe ser igual a <code>25</code>
|
||||
testString: 'assert(a === 25, "<code>a</code> should equal <code>25</code>");'
|
||||
- text: <code>b</code> debe ser igual a <code>36</code>
|
||||
testString: 'assert(b === 36, "<code>b</code> should equal <code>36</code>");'
|
||||
- text: <code>c</code> debería ser igual a <code>46</code>
|
||||
testString: 'assert(c === 46, "<code>c</code> should equal <code>46</code>");'
|
||||
- text: Debes usar el operador <code>*=</code> para cada variable
|
||||
testString: 'assert(code.match(/\*=/g).length === 3, "You should use the <code>*=</code> operator for each variable");'
|
||||
- text: No modifique el código sobre la línea.
|
||||
testString: 'assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\.6;/.test(code), "Do not modify the code above the line");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
// Only modify code below this line
|
||||
|
||||
a = a * 5;
|
||||
b = 3 * b;
|
||||
c = c * 10;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
a *= 5;
|
||||
b *= 3;
|
||||
c *= 10;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b0
|
||||
title: Compound Assignment With Augmented Subtraction
|
||||
localeTitle: Asignación compuesta con resta aumentada
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Al igual que el operador <code>+=</code> , <code>-=</code> resta un número de una variable.
|
||||
<code>myVar = myVar - 5;</code>
|
||||
restará <code>5</code> de <code>myVar</code> . Esto se puede reescribir como:
|
||||
<code>myVar -= 5;</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Convierta las asignaciones para <code>a</code> , <code>b</code> y <code>c</code> para usar el operador <code>-=</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>a</code> debe ser igual a <code>5</code>
|
||||
testString: 'assert(a === 5, "<code>a</code> should equal <code>5</code>");'
|
||||
- text: <code>b</code> debería ser igual a <code>-6</code>
|
||||
testString: 'assert(b === -6, "<code>b</code> should equal <code>-6</code>");'
|
||||
- text: <code>c</code> debería ser igual a <code>2</code>
|
||||
testString: 'assert(c === 2, "<code>c</code> should equal <code>2</code>");'
|
||||
- text: Debe usar el operador <code>-=</code> para cada variable
|
||||
testString: 'assert(code.match(/-=/g).length === 3, "You should use the <code>-=</code> operator for each variable");'
|
||||
- text: No modifique el código sobre la línea.
|
||||
testString: 'assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code), "Do not modify the code above the line");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
// Only modify code below this line
|
||||
|
||||
a = a - 6;
|
||||
b = b - 15;
|
||||
c = c - 1;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
a -= 6;
|
||||
b -= 15;
|
||||
c -= 1;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b7
|
||||
title: Concatenating Strings with Plus Operator
|
||||
localeTitle: Concatenando cuerdas con el operador Plus
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En JavaScript, cuando el operador <code>+</code> se usa con un valor de <code>String</code> , se llama operador de <dfn>concatenación</dfn> . Puede construir una nueva cadena a partir de otras cadenas <dfn>concatenándolas</dfn> juntas.
|
||||
<strong>Ejemplo</strong>
|
||||
<blockquote>'My name is Alan,' + ' I concatenate.'</blockquote>
|
||||
<strong>Nota</strong> <br> Cuidado con los espacios. La concatenación no agrega espacios entre las cadenas concatenadas, por lo que deberá agregarlas usted mismo.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Construye <code>myStr</code> partir de las cadenas <code>"This is the start. "</code> y <code>"This is the end."</code> utilizando el operador <code>+</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myStr</code> debe tener un valor de <code>This is the start. This is the end.</code>
|
||||
testString: 'assert(myStr === "This is the start. This is the end.", "<code>myStr</code> should have a value of <code>This is the start. This is the end.</code>");'
|
||||
- text: Usa el operador <code>+</code> para construir <code>myStr</code>
|
||||
testString: 'assert(code.match(/([""]).*([""])\s*\+\s*([""]).*([""])/g).length > 1, "Use the <code>+</code> operator to build <code>myStr</code>");'
|
||||
- text: <code>myStr</code> debe crearse usando la palabra clave <code>var</code> .
|
||||
testString: 'assert(/var\s+myStr/.test(code), "<code>myStr</code> should be created using the <code>var</code> keyword.");'
|
||||
- text: Asegúrese de asignar el resultado a la variable <code>myStr</code> .
|
||||
testString: 'assert(/myStr\s*=/.test(code), "Make sure to assign the result to the <code>myStr</code> variable.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var myStr;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
var myStr = "This is the start. " + "This is the end.";
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b8
|
||||
title: Concatenating Strings with the Plus Equals Operator
|
||||
localeTitle: Concatenando cadenas con el operador Plus Equals
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
También podemos usar el operador <code>+=</code> para <dfn>concatenar</dfn> una cadena al final de una variable de cadena existente. Esto puede ser muy útil para romper una cadena larga en varias líneas.
|
||||
<strong>Nota</strong> <br> Cuidado con los espacios. La concatenación no agrega espacios entre las cadenas concatenadas, por lo que deberá agregarlas usted mismo.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Construya <code>myStr</code> en varias líneas concatenando estas dos cadenas: <code>"This is the first sentence. "</code> y <code>"This is the second sentence."</code> utilizando el operador <code>+=</code> . Utilice el operador <code>+=</code> similar a como se muestra en el editor. Comience por asignar la primera cadena a <code>myStr</code> , luego agregue la segunda cadena.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myStr</code> debe tener un valor de <code>This is the first sentence. This is the second sentence.</code>
|
||||
testString: 'assert(myStr === "This is the first sentence. This is the second sentence.", "<code>myStr</code> should have a value of <code>This is the first sentence. This is the second sentence.</code>");'
|
||||
- text: Usa el operador <code>+=</code> para construir <code>myStr</code>
|
||||
testString: 'assert(code.match(/\w\s*\+=\s*[""]/g).length > 1 && code.match(/\w\s*\=\s*[""]/g).length > 1, "Use the <code>+=</code> operator to build <code>myStr</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourStr = "I come first. ";
|
||||
ourStr += "I come second.";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var myStr;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. ";
|
||||
ourStr += "I come second.";
|
||||
|
||||
var myStr = "This is the first sentence. ";
|
||||
myStr += "This is the second sentence.";
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b9
|
||||
title: Constructing Strings with Variables
|
||||
localeTitle: Construyendo cuerdas con variables
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
A veces necesitarás construir una cadena, al estilo de <a href="https://en.wikipedia.org/wiki/Mad_Libs" target="_blank">Mad Libs</a> . Al utilizar el operador de concatenación ( <code>+</code> ), puede insertar una o más variables en una cadena que está creando.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Establezca <code>myName</code> en una cadena igual a su nombre y compile <code>myStr</code> con <code>myName</code> entre las cadenas <code>"My name is "</code> y <code>" and I am well!"</code>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myName</code> debe establecerse en una cadena de al menos 3 caracteres
|
||||
testString: 'assert(typeof myName !== "undefined" && myName.length > 2, "<code>myName</code> should be set to a string at least 3 characters long");'
|
||||
- text: Usa dos operadores <code>+</code> para construir <code>myStr</code> con <code>myName</code> dentro de él
|
||||
testString: 'assert(code.match(/[""]\s*\+\s*myName\s*\+\s*[""]/g).length > 0, "Use two <code>+</code> operators to build <code>myStr</code> with <code>myName</code> inside it");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourName = "freeCodeCamp";
|
||||
var ourStr = "Hello, our name is " + ourName + ", how are you?";
|
||||
|
||||
// Only change code below this line
|
||||
var myName;
|
||||
var myStr;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myName = "Bob";
|
||||
var myStr = "My name is " + myName + " and I am well!";
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 56105e7b514f539506016a5e
|
||||
title: Count Backwards With a For Loop
|
||||
localeTitle: Contar hacia atrás con un bucle for
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
A for loop también puede contar hacia atrás, siempre que podamos definir las condiciones correctas.
|
||||
Para contar hacia atrás de dos en dos, necesitaremos cambiar nuestra <code>initialization</code> , <code>condition</code> y <code>final-expression</code> .
|
||||
Comenzaremos en <code>i = 10</code> y haremos un bucle mientras <code>i > 0</code> . Disminuiremos <code>i</code> en 2 cada bucle con <code>i -= 2</code> .
|
||||
<blockquote>var ourArray = [];<br>for (var i=10; i > 0; i-=2) {<br> ourArray.push(i);<br>}</blockquote>
|
||||
<code>ourArray</code> ahora contendrá <code>[10,8,6,4,2]</code> .
|
||||
Cambiemos nuestra <code>initialization</code> y <code>final-expression</code> para que podamos contar hacia atrás de dos en dos con números impares.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Empuje los números impares del 9 al 1 a <code>myArray</code> usando un bucle <code>for</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Usted debe estar usando una <code>for</code> bucle para esto.
|
||||
testString: 'assert(code.match(/for\s*\(/g).length > 1, "You should be using a <code>for</code> loop for this.");'
|
||||
- text: Deberías estar usando el método de matriz <code>push</code> .
|
||||
testString: 'assert(code.match(/myArray.push/), "You should be using the array method <code>push</code>.");'
|
||||
- text: ' <code>myArray</code> debe ser igual a <code>[9,7,5,3,1]</code> .'
|
||||
testString: 'assert.deepEqual(myArray, [9,7,5,3,1], "<code>myArray</code> should equal <code>[9,7,5,3,1]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourArray = [];
|
||||
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
var myArray = [];
|
||||
for (var i = 9; i > 0; i -= 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,104 @@
|
||||
---
|
||||
id: 565bbe00e9cc8ac0725390f4
|
||||
title: Counting Cards
|
||||
localeTitle: Tarjetas de conteo
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En el juego de casino Blackjack, un jugador puede obtener una ventaja sobre la casa al hacer un seguimiento del número relativo de cartas altas y bajas que quedan en el mazo. Esto se llama <a href='https://en.wikipedia.org/wiki/Card_counting' target='_blank'>conteo de cartas</a> .
|
||||
Tener más cartas altas en el mazo favorece al jugador. A cada tarjeta se le asigna un valor de acuerdo con la siguiente tabla. Cuando el conteo es positivo, el jugador debe apostar alto. Cuando el conteo es cero o negativo, el jugador debe apostar bajo.
|
||||
<table class="table table-striped"><thead><tr><th> Cambio de cuenta </th><th> Tarjetas </th></tr></thead><tbody><tr><td> +1 </td><td> 2, 3, 4, 5, 6 </td></tr><tr><td> 0 </td><td> 7, 8, 9 </td></tr><tr><td> -1 </td><td> 10, 'J', 'Q', 'K', 'A' </td></tr></tbody></table>
|
||||
Escribirás una función de conteo de cartas. Recibirá un parámetro de <code>card</code> , que puede ser un número o una cadena, y aumentará o disminuirá la variable de <code>count</code> global según el valor de la tarjeta (consulte la tabla). La función devolverá una cadena con el recuento actual y la cadena <code>Bet</code> si el recuento es positivo, o <code>Hold</code> si el recuento es cero o negativo. El conteo actual y la decisión del jugador ( <code>Bet</code> o <code>Hold</code> ) deben estar separados por un solo espacio.
|
||||
<strong>Ejemplo de salida</strong> <br> <code>-3 Hold</code> <br> <code>5 Bet</code>
|
||||
<strong>Sugerencia</strong> <br> NO reinicie el <code>count</code> a 0 cuando el valor sea 7, 8 o 9. <br> NO devuelva una matriz. <br> NO incluya comillas (simples o dobles) en la salida.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'Las secuencias de cartas 2, 3, 4, 5, 6 deben devolver <code>5 Bet</code> '
|
||||
testString: 'assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === "5 Bet") {return true;} return false; })(), "Cards Sequence 2, 3, 4, 5, 6 should return <code>5 Bet</code>");'
|
||||
- text: 'Las secuencias de cartas 7, 8, 9 deben devolver <code>0 Hold</code> '
|
||||
testString: 'assert((function(){ count = 0; cc(7);cc(8);var out = cc(9); if(out === "0 Hold") {return true;} return false; })(), "Cards Sequence 7, 8, 9 should return <code>0 Hold</code>");'
|
||||
- text: 'La secuencia de cartas 10, J, Q, K, A debería devolver <code>-5 Hold</code> '
|
||||
testString: 'assert((function(){ count = 0; cc(10);cc("J");cc("Q");cc("K");var out = cc("A"); if(out === "-5 Hold") {return true;} return false; })(), "Cards Sequence 10, J, Q, K, A should return <code>-5 Hold</code>");'
|
||||
- text: 'Las secuencias de cartas 3, 7, Q, 8, A deben devolver <code>-1 Hold</code> '
|
||||
testString: 'assert((function(){ count = 0; cc(3);cc(7);cc("Q");cc(8);var out = cc("A"); if(out === "-1 Hold") {return true;} return false; })(), "Cards Sequence 3, 7, Q, 8, A should return <code>-1 Hold</code>");'
|
||||
- text: 'Las secuencias de cartas 2, J, 9, 2, 7 deben devolver <code>1 Bet</code> '
|
||||
testString: 'assert((function(){ count = 0; cc(2);cc("J");cc(9);cc(2);var out = cc(7); if(out === "1 Bet") {return true;} return false; })(), "Cards Sequence 2, J, 9, 2, 7 should return <code>1 Bet</code>");'
|
||||
- text: 'Las secuencias de cartas 2, 2, 10 deben devolver <code>1 Bet</code> '
|
||||
testString: 'assert((function(){ count = 0; cc(2);cc(2);var out = cc(10); if(out === "1 Bet") {return true;} return false; })(), "Cards Sequence 2, 2, 10 should return <code>1 Bet</code>");'
|
||||
- text: 'Secuencia de cartas 3, 2, A, 10, K debería devolver <code>-1 Hold</code> '
|
||||
testString: 'assert((function(){ count = 0; cc(3);cc(2);cc("A");cc(10);var out = cc("K"); if(out === "-1 Hold") {return true;} return false; })(), "Cards Sequence 3, 2, A, 10, K should return <code>-1 Hold</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
|
||||
function cc(card) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
// Add/remove calls to test your function.
|
||||
// Note: Only the last will display
|
||||
cc(2); cc(3); cc(7); cc('K'); cc('A');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
function cc(card) {
|
||||
switch(card) {
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
count++;
|
||||
break;
|
||||
case 10:
|
||||
case 'J':
|
||||
case 'Q':
|
||||
case 'K':
|
||||
case 'A':
|
||||
count--;
|
||||
}
|
||||
if(count > 0) {
|
||||
return count + " Bet";
|
||||
} else {
|
||||
return count + " Hold";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,68 @@
|
||||
---
|
||||
id: cf1391c1c11feddfaeb4bdef
|
||||
title: Create Decimal Numbers with JavaScript
|
||||
localeTitle: Crea números decimales con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Podemos almacenar números decimales en variables también. Los números decimales a veces se denominan números de <dfn>punto flotante</dfn> o <dfn>flotantes</dfn> .
|
||||
<strong>Nota</strong> <br> No todos los números reales se pueden representar con precisión en <dfn>coma flotante</dfn> . Esto puede llevar a errores de redondeo. <a href="https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems" target="_blank">Detalles aquí</a> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Crea una variable <code>myDecimal</code> y dale un valor decimal con una parte fraccionaria (por ejemplo, <code>5.7</code> ).
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myDecimal</code> debe ser un número.
|
||||
testString: 'assert(typeof myDecimal === "number", "<code>myDecimal</code> should be a number.");'
|
||||
- text: <code>myDecimal</code> debería tener un punto decimal
|
||||
testString: 'assert(myDecimal % 1 != 0, "<code>myDecimal</code> should have a decimal point"); '
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var ourDecimal = 5.7;
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myDecimal = 9.9;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: bd7123c9c443eddfaeb5bdef
|
||||
title: Declare JavaScript Variables
|
||||
localeTitle: Declarar las variables de JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En informática, los <dfn>datos</dfn> son cualquier cosa que sea significativa para la computadora. JavaScript proporciona siete <dfn>tipos de datos diferentes</dfn> que son <code>undefined</code> , <code>null</code> , <code>boolean</code> , <code>string</code> , <code>symbol</code> , <code>number</code> y <code>object</code> .
|
||||
Por ejemplo, las computadoras distinguen entre los números, como el número <code>12</code> , y las <code>strings</code> , como <code>"12"</code> , <code>"dog"</code> o <code>"123 cats"</code> , que son colecciones de caracteres. Las computadoras pueden realizar operaciones matemáticas en un número, pero no en una cadena.
|
||||
<dfn>Las variables</dfn> permiten que las computadoras almacenen y manipulen datos de una manera dinámica. Hacen esto usando una "etiqueta" para señalar los datos en lugar de usar los datos en sí. Cualquiera de los siete tipos de datos puede almacenarse en una variable.
|
||||
<code>Variables</code> son similares a las variables x e y que usa en matemáticas, lo que significa que son un nombre simple para representar los datos a los que queremos referirnos. Las <code>variables</code> computadora difieren de las variables matemáticas en que pueden almacenar diferentes valores en diferentes momentos.
|
||||
Le pedimos a JavaScript que cree o <dfn>declare</dfn> una variable poniendo la palabra clave <code>var</code> delante de ella, así:
|
||||
<blockquote>var ourName;</blockquote>
|
||||
crea una <code>variable</code> llamada <code>ourName</code> . En JavaScript terminamos las frases con punto y coma.
|
||||
<code>Variable</code> nombres de las <code>Variable</code> pueden estar formados por números, letras y <code>$</code> o <code>_</code> , pero no pueden contener espacios ni comenzar con un número.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use la palabra clave <code>var</code> para crear una variable llamada <code>myName</code> .
|
||||
<strong>Pista</strong> <br> Mira el ejemplo de <code>ourName</code> si te quedas atascado.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'Debes declarar <code>myName</code> con la palabra clave <code>var</code> , que termina con un punto y coma'
|
||||
testString: 'assert(/var\s+myName\s*;/.test(code), "You should declare <code>myName</code> with the <code>var</code> keyword, ending with a semicolon");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourName;
|
||||
|
||||
// Declare myName below this line
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myName;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: bd7123c9c444eddfaeb5bdef
|
||||
title: Declare String Variables
|
||||
localeTitle: Declarar variables de cadena
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Anteriormente hemos utilizado el código
|
||||
<code>var myName = "your name";</code>
|
||||
<code>"your name"</code> se llama una <dfn>cadena</dfn> <dfn>literal</dfn> . Es una cadena porque es una serie de cero o más caracteres entre comillas simples o dobles.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Crea dos nuevas variables de <code>string</code> : <code>myFirstName</code> y <code>myLastName</code> y asigna los valores de tu nombre y apellido, respectivamente.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myFirstName</code> debe ser una cadena con al menos un carácter.
|
||||
testString: 'assert((function(){if(typeof myFirstName !== "undefined" && typeof myFirstName === "string" && myFirstName.length > 0){return true;}else{return false;}})(), "<code>myFirstName</code> should be a string with at least one character in it.");'
|
||||
- text: <code>myLastName</code> debe ser una cadena con al menos un carácter.
|
||||
testString: 'assert((function(){if(typeof myLastName !== "undefined" && typeof myLastName === "string" && myLastName.length > 0){return true;}else{return false;}})(), "<code>myLastName</code> should be a string with at least one character in it.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var firstName = "Alan";
|
||||
var lastName = "Turing";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myFirstName = "Alan";
|
||||
var myLastName = "Turing";
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ad
|
||||
title: Decrement a Number with JavaScript
|
||||
localeTitle: Disminuir un número con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Puede <dfn>disminuir</dfn> o disminuir fácilmente una variable por una con el operador <code>--</code> .
|
||||
<code>i--;</code>
|
||||
es el equivalente de
|
||||
<code>i = i - 1;</code>
|
||||
<strong>Nota</strong> <br> La línea entera se convierte en <code>i--;</code> , eliminando la necesidad del signo igual.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambie el código para usar el operador <code>--</code> en <code>myVar</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myVar</code> debe ser igual a <code>10</code>
|
||||
testString: 'assert(myVar === 10, "<code>myVar</code> should equal <code>10</code>");'
|
||||
- text: <code>myVar = myVar - 1;</code> debería ser cambiado
|
||||
testString: 'assert(/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code), "<code>myVar = myVar - 1;</code> should be changed");'
|
||||
- text: Utilice el <code>--</code> operador en <code>myVar</code>
|
||||
testString: 'assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code), "Use the <code>--</code> operator on <code>myVar</code>");'
|
||||
- text: No cambie el código por encima de la línea
|
||||
testString: 'assert(/var myVar = 11;/.test(code), "Do not change code above the line");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar - 1;
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
myVar--;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,100 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d3
|
||||
title: Delete Properties from a JavaScript Object
|
||||
localeTitle: Eliminar propiedades de un objeto de JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
También podemos eliminar propiedades de objetos como este:
|
||||
<code>delete ourDog.bark;</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Eliminar la propiedad <code>"tails"</code> de <code>myDog</code> . Puede usar la notación de punto o corchete.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Eliminar la propiedad <code>"tails"</code> de <code>myDog</code> .
|
||||
testString: 'assert(typeof myDog === "object" && myDog.tails === undefined, "Delete the property <code>"tails"</code> from <code>myDog</code>.");'
|
||||
- text: No modifique la configuración de <code>myDog</code>
|
||||
testString: 'assert(code.match(/"tails": 1/g).length > 1, "Do not modify the <code>myDog</code> setup");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"],
|
||||
"bark": "bow-wow"
|
||||
};
|
||||
|
||||
delete ourDog.bark;
|
||||
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"],
|
||||
"bark": "bow-wow"
|
||||
};
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
delete myDog.tails;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,65 @@
|
||||
---
|
||||
id: bd7993c9ca9feddfaeb7bdef
|
||||
title: Divide One Decimal by Another with JavaScript
|
||||
localeTitle: Divide un decimal por otro con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Ahora dividamos un decimal por otro.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambie el <code>0.0</code> para que el <code>quotient</code> sea igual a <code>2.2</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: El <code>quotient</code> variable debe ser igual a <code>2.2</code>
|
||||
testString: 'assert(quotient === 2.2, "The variable <code>quotient</code> should equal <code>2.2</code>");'
|
||||
- text: Debes usar el operador <code>/</code> para dividir 4.4 por 2
|
||||
testString: 'assert(/4\.40*\s*\/\s*2\.*0*/.test(code), "You should use the <code>/</code> operator to divide 4.4 by 2");'
|
||||
- text: La variable de cociente solo debe ser asignada una vez.
|
||||
testString: 'assert(code.match(/quotient/g).length === 1, "The quotient variable should only be assigned once");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var quotient = 0.0 / 2.0; // Fix this line
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb6bdef
|
||||
title: Divide One Number by Another with JavaScript
|
||||
localeTitle: Divide un número por otro con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
También podemos dividir un número por otro.
|
||||
JavaScript usa el símbolo <code>/</code> para la división.
|
||||
|
||||
<strong>Ejemplo</strong>
|
||||
<blockquote>myVar = 16 / 2; // assigned 8</blockquote>
|
||||
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambia el <code>0</code> para que el <code>quotient</code> sea igual a <code>2</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Haz que el <code>quotient</code> variable sea igual a 2.
|
||||
testString: 'assert(quotient === 2, "Make the variable <code>quotient</code> equal to 2.");'
|
||||
- text: Usa el operador <code>/</code>
|
||||
testString: 'assert(/\d+\s*\/\s*\d+/.test(code), "Use the <code>/</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var quotient = 66 / 0;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var quotient = 66 / 33;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b6
|
||||
title: Escape Sequences in Strings
|
||||
localeTitle: Secuencias de escape en cuerdas
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
comillas no son los únicos caracteres que pueden <dfn>escaparse</dfn> dentro de una cadena. Hay dos razones para usar caracteres que se escapan: primero es permitirle usar caracteres que de otra forma no podría escribir, como un retroceso. El segundo es permitirte representar múltiples citas en una cadena sin que JavaScript interprete mal lo que quieres decir. Aprendimos esto en el reto anterior.
|
||||
<table class="table table-striped"><thead><tr><th> Código </th><th> Salida </th></tr></thead><tbody><tr><td> <code>\'</code> </td> <td> una frase </td></tr><tr><td> <code>\"</code> </td> <td> doble cita </td></tr><tr><td> <code>\\</code> </td> <td> barra invertida </td></tr><tr><td> <code>\n</code> </td> <td> nueva línea </td></tr><tr><td> <code>\r</code> </td> <td> retorno de carro </td></tr><tr><td> <code>\t</code> </td> <td> lengüeta </td></tr><tr><td> <code>\b</code> </td> <td> retroceso </td></tr><tr><td> <code>\f</code> </td> <td> form feed </td></tr></tbody></table>
|
||||
<em>Tenga en cuenta que la barra invertida debe escaparse para que se muestre como una barra invertida.</em>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Asigne las siguientes tres líneas de texto a la única variable <code>myStr</code> usando secuencias de escape.
|
||||
<blockquote>FirstLine<br/> \SecondLine<br/>ThirdLine</blockquote>
|
||||
Necesitará usar secuencias de escape para insertar caracteres especiales correctamente. También deberá seguir el espaciado como se ve arriba, sin espacios entre las secuencias de escape o las palabras.
|
||||
Aquí está el texto con las secuencias de escape escritas.
|
||||
<q>FirstLine <code>newline</code> <code>tab</code> <code>backslash</code> SecondLine <code>newline</code> ThirdLine</q>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myStr</code> no debe contener espacios
|
||||
testString: 'assert(!/ /.test(myStr), "<code>myStr</code> should not contain any spaces");'
|
||||
- text: ' <code>myStr</code> debe contener las cadenas <code>FirstLine</code> , <code>SecondLine</code> y <code>ThirdLine</code> (recuerda la sensibilidad a los casos)'
|
||||
testString: 'assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), "<code>myStr</code> should contain the strings <code>FirstLine</code>, <code>SecondLine</code> and <code>ThirdLine</code> (remember case sensitivity)");'
|
||||
- text: <code>FirstLine</code> debe ir seguido del carácter de nueva línea <code>\n</code>
|
||||
testString: 'assert(/FirstLine\n/.test(myStr), "<code>FirstLine</code> should be followed by the newline character <code>\n</code>");'
|
||||
- text: <code>myStr</code> debe contener un carácter de tabulación <code>\t</code> que sigue a un carácter de nueva línea
|
||||
testString: 'assert(/\n\t/.test(myStr), "<code>myStr</code> should contain a tab character <code>\t</code> which follows a newline character");'
|
||||
- text: <code>SecondLine</code> debe ir precedida por el carácter de barra invertida <code>\\</code>
|
||||
testString: 'assert(/\SecondLine/.test(myStr), "<code>SecondLine</code> should be preceded by the backslash character <code>\\</code>");'
|
||||
- text: Debe haber un carácter de nueva línea entre <code>SecondLine</code> y <code>ThirdLine</code>
|
||||
testString: 'assert(/SecondLine\nThirdLine/.test(myStr), "There should be a newline character between <code>SecondLine</code> and <code>ThirdLine</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b5
|
||||
title: Escaping Literal Quotes in Strings
|
||||
localeTitle: Escapar de citas literales en cuerdas
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Cuando está definiendo una cadena, debe comenzar y terminar con una comilla simple o doble. ¿Qué sucede cuando necesita una cita literal: <code>"</code> o <code>'</code> dentro de su cadena?
|
||||
En JavaScript, puede <dfn>evitar que</dfn> una cita la considere como un final de cadena de la cadena colocando una <dfn>barra invertida</dfn> ( <code>\</code> ) delante de la cita.
|
||||
<code>var sampleStr = "Alan said, \"Peter is learning JavaScript\".";</code>
|
||||
Esto indica a JavaScript que la siguiente cita no es el final de la cadena, sino que debería aparecer dentro de la cadena. Por lo tanto, si imprimiera esto en En la consola, obtendrías:
|
||||
<code>Alan said, "Peter is learning JavaScript".</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use <dfn>barras diagonales inversas</dfn> para asignar una cadena a la variable <code>myStr</code> modo que si tuviera que imprimirla en la consola, verá:
|
||||
<code>I am a "double quoted" string inside "double quotes".</code>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'Debería usar dos comillas dobles ( <code>"</code> ) y cuatro comillas dobles escapadas ( <code>\"</code> ).'
|
||||
testString: 'assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2, "You should use two double quotes (<code>"</code>) and four escaped double quotes (<code>\"</code>).");'
|
||||
- text: 'Variable myStr debe contener la cadena: <code>I am a "double quoted" string inside "double quotes".</code> comilla <code>I am a "double quoted" string inside "double quotes".</code> '
|
||||
testString: 'assert(myStr === "I am a \"double quoted\" string inside \"double quotes\".", "Variable myStr should contain the string: <code>I am a "double quoted" string inside "double quotes".</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var myStr = ""; // Change this line
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,85 @@
|
||||
---
|
||||
id: bd7123c9c448eddfaeb5bdef
|
||||
title: Find the Length of a String
|
||||
localeTitle: Encuentra la longitud de una cuerda
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Puede encontrar la longitud de un valor de <code>String</code> escribiendo <code>.length</code> después de la variable de cadena o el literal de cadena.
|
||||
<code>"Alan Peter".length; // 10</code>
|
||||
Por ejemplo, si creamos una variable <code>var firstName = "Charles"</code> , podríamos averiguar cuánto tiempo dura la cadena <code>"Charles"</code> utilizando la propiedad <code>firstName.length</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use la propiedad <code>.length</code> para contar el número de caracteres en la variable <code>lastName</code> y asignarla a <code>lastNameLength</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>lastNameLength</code> debe ser igual a ocho.
|
||||
testString: 'assert((function(){if(typeof lastNameLength !== "undefined" && typeof lastNameLength === "number" && lastNameLength === 8){return true;}else{return false;}})(), "<code>lastNameLength</code> should be equal to eight.");'
|
||||
- text: 'Deberías obtener la longitud del <code>lastName</code> al usar <code>.length</code> esta manera: <code>lastName.length</code> '.
|
||||
testString: 'assert((function(){if(code.match(/\.length/gi) && code.match(/\.length/gi).length >= 2 && code.match(/var lastNameLength \= 0;/gi) && code.match(/var lastNameLength \= 0;/gi).length >= 1){return true;}else{return false;}})(), "You should be getting the length of <code>lastName</code> by using <code>.length</code> like this: <code>lastName.length</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var firstNameLength = 0;
|
||||
var firstName = "Ada";
|
||||
|
||||
firstNameLength = firstName.length;
|
||||
|
||||
// Setup
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
lastNameLength = lastName;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var firstNameLength = 0;
|
||||
var firstName = "Ada";
|
||||
firstNameLength = firstName.length;
|
||||
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
lastNameLength = lastName.length;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ae
|
||||
title: Finding a Remainder in JavaScript
|
||||
localeTitle: Encontrar un resto en JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El operador <dfn>restante</dfn> <code>%</code> da el resto de la división de dos números.
|
||||
<strong>Ejemplo</strong>
|
||||
<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>
|
||||
<strong>Usage</strong> <br> En matemáticas, se puede verificar que un número sea par o impar verificando el resto de la división del número entre <code>2</code> .
|
||||
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
|
||||
<strong>Nota</strong> <br> El operador del <dfn>resto a</dfn> veces se denomina incorrectamente operador del "módulo". Es muy similar al módulo, pero no funciona correctamente con números negativos.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Establezca el <code>remainder</code> igual al resto de <code>11</code> dividido por <code>3</code> usando el operador <dfn>resto</dfn> ( <code>%</code> ).
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>remainder</code> debe ser inicializada.
|
||||
testString: 'assert(/var\s+?remainder/.test(code), "The variable <code>remainder</code> should be initialized");'
|
||||
- text: El valor del <code>remainder</code> debe ser <code>2</code>
|
||||
testString: 'assert(remainder === 2, "The value of <code>remainder</code> should be <code>2</code>");'
|
||||
- text: Debes usar el operador <code>%</code>
|
||||
testString: 'assert(/\s+?remainder\s*?=\s*?.*%.*;/.test(code), "You should use the <code>%</code> operator");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
|
||||
var remainder;
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var remainder = 11 % 3;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb9bdef
|
||||
title: Generate Random Fractions with JavaScript
|
||||
localeTitle: Generar fracciones aleatorias con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Los números aleatorios son útiles para crear un comportamiento aleatorio.
|
||||
JavaScript tiene una función <code>Math.random()</code> que genera un número decimal aleatorio entre <code>0</code> (incluido) y no hasta <code>1</code> (exclusivo). Por <code>Math.random()</code> tanto, <code>Math.random()</code> puede devolver un <code>0</code> pero nunca devolver completamente una <strong>Nota de</strong> <code>1</code>
|
||||
<br> Al igual que el <a href='storing-values-with-the-assignment-operator' target='_blank'>almacenamiento de valores con el operador igual</a> , todas las llamadas de función se resolverán antes de que se ejecute la <code>return</code> , por lo que podemos <code>return</code> el valor de la función <code>Math.random()</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambie <code>randomFraction</code> para devolver un número aleatorio en lugar de devolver <code>0</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>randomFraction</code> debería devolver un número aleatorio.
|
||||
testString: 'assert(typeof randomFraction() === "number", "<code>randomFraction</code> should return a random number.");'
|
||||
- text: El número devuelto por <code>randomFraction</code> debe ser un decimal.
|
||||
testString: 'assert((randomFraction()+""). match(/\./g), "The number returned by <code>randomFraction</code> should be a decimal.");'
|
||||
- text: Debería estar usando <code>Math.random</code> para generar el número decimal aleatorio.
|
||||
testString: 'assert(code.match(/Math\.random/g).length >= 0, "You should be using <code>Math.random</code> to generate the random decimal number.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
return 0;
|
||||
|
||||
// Only change code above this line.
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
return Math.random();
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb1bdef
|
||||
title: Generate Random Whole Numbers with JavaScript
|
||||
localeTitle: Generar números enteros al azar con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Es genial que podamos generar números decimales aleatorios, pero es aún más útil si lo usamos para generar números enteros aleatorios.
|
||||
<ol><li> Usa <code>Math.random()</code> para generar un decimal aleatorio. </li><li> Multiplica ese decimal aleatorio por <code>20</code> . </li><li> Use otra función, <code>Math.floor()</code> para redondear el número a su número entero más cercano. </li></ol>
|
||||
Recuerda que <code>Math.random()</code> nunca puede devolver un <code>1</code> y, porque estamos redondeando, es imposible obtener <code>20</code> . Esta técnica nos dará un número entero entre <code>0</code> y <code>19</code> .
|
||||
Poniendo todo junto, así es como se ve nuestro código:
|
||||
<code>Math.floor(Math.random() * 20);</code>
|
||||
Estamos llamando a <code>Math.random()</code> , multiplicamos el resultado por 20 y luego <code>Math.floor()</code> el valor a la función <code>Math.floor()</code> para redondear el valor al número entero más cercano.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use esta técnica para generar y devolver un número entero aleatorio entre <code>0</code> y <code>9</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: El resultado de <code>randomWholeNum</code> debe ser un número entero.
|
||||
testString: 'assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), "The result of <code>randomWholeNum</code> should be a whole number.");'
|
||||
- text: Debería estar usando <code>Math.random</code> para generar un número aleatorio.
|
||||
testString: 'assert(code.match(/Math.random/g).length > 1, "You should be using <code>Math.random</code> to generate a random number.");'
|
||||
- text: Debería haber multiplicado el resultado de <code>Math.random</code> por 10 para que sea un número entre cero y nueve.
|
||||
testString: 'assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g), "You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.");'
|
||||
- text: Debe usar <code>Math.floor</code> para eliminar la parte decimal del número.
|
||||
testString: 'assert(code.match(/Math.floor/g).length > 1, "You should use <code>Math.floor</code> to remove the decimal part of the number.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
|
||||
|
||||
function randomWholeNum() {
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
return Math.random();
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
|
||||
function randomWholeNum() {
|
||||
return Math.floor(Math.random() * 10);
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb2bdef
|
||||
title: Generate Random Whole Numbers within a Range
|
||||
localeTitle: Generar números enteros al azar dentro de un rango
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En lugar de generar un número aleatorio entre cero y un número dado como hicimos antes, podemos generar un número aleatorio que se encuentre dentro de un rango de dos números específicos.
|
||||
Para hacer esto, definiremos un número mínimo <code>min</code> y un máximo número <code>max</code> .
|
||||
Aquí está la fórmula que usaremos. Tómese un momento para leerlo e intente entender lo que hace este código:
|
||||
<code>Math.floor(Math.random() * (max - min + 1)) + min</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cree una función llamada <code>randomRange</code> que tome un rango <code>myMin</code> y <code>myMax</code> y devuelva un número aleatorio que sea mayor o igual que <code>myMin</code> , y que sea menor o igual que <code>myMax</code> , inclusive.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: 'El número aleatorio más bajo que puede ser generado por <code>randomRange</code> debería ser igual a tu número mínimo, <code>myMin</code> '.
|
||||
testString: 'assert(calcMin === 5, "The lowest random number that can be generated by <code>randomRange</code> should be equal to your minimum number, <code>myMin</code>.");'
|
||||
- text: "El número aleatorio más alto que puede ser generado por <code>randomRange</code> debería ser igual a tu número máximo, <code>myMax</code> ".
|
||||
testString: 'assert(calcMax === 15, "The highest random number that can be generated by <code>randomRange</code> should be equal to your maximum number, <code>myMax</code>.");'
|
||||
- text: 'El número aleatorio generado por <code>randomRange</code> debe ser un número entero, no un decimal'.
|
||||
testString: 'assert(randomRange(0,1) % 1 === 0 , "The random number generated by <code>randomRange</code> should be an integer, not a decimal.");'
|
||||
- text: ' <code>randomRange</code> debe usar <code>myMax</code> y <code>myMin</code> , y devolver un número aleatorio en tu rango'.
|
||||
testString: 'assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), "<code>randomRange</code> should use both <code>myMax</code> and <code>myMin</code>, and return a random number in your range.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
function ourRandomRange(ourMin, ourMax) {
|
||||
|
||||
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
|
||||
}
|
||||
|
||||
ourRandomRange(1, 9);
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
function randomRange(myMin, myMax) {
|
||||
|
||||
return 0; // Change this line
|
||||
|
||||
}
|
||||
|
||||
// Change these values to test your function
|
||||
var myRandom = randomRange(5, 15);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function randomRange(myMin, myMax) {
|
||||
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,132 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244be
|
||||
title: Global Scope and Functions
|
||||
localeTitle: Ámbito global y funciones
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En JavaScript, el <dfn>alcance se</dfn> refiere a la visibilidad de las variables. Las variables que se definen fuera de un bloque de función tienen alcance <dfn>global</dfn> . Esto significa que pueden verse en todas partes en su código JavaScript.
|
||||
Las variables que se utilizan sin la palabra clave <code>var</code> se crean automáticamente en el ámbito <code>global</code> . Esto puede crear consecuencias no deseadas en otra parte de su código o al ejecutar una función nuevamente. Siempre debes declarar tus variables con <code>var</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Usando <code>var</code> , declare una variable <code>global</code> <code>myGlobal</code> fuera de cualquier función. Inicialízalo con un valor de <code>10</code> .
|
||||
Dentro de la función <code>fun1</code> , asigne <code>5</code> a <code>oopsGlobal</code> <strong><em>sin</em></strong> usar la palabra clave <code>var</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myGlobal</code> debe ser definido
|
||||
testString: 'assert(typeof myGlobal != "undefined", "<code>myGlobal</code> should be defined");'
|
||||
- text: <code>myGlobal</code> debe tener un valor de <code>10</code>
|
||||
testString: 'assert(myGlobal === 10, "<code>myGlobal</code> should have a value of <code>10</code>");'
|
||||
- text: <code>myGlobal</code> debe declararse usando la palabra clave <code>var</code>
|
||||
testString: 'assert(/var\s+myGlobal/.test(code), "<code>myGlobal</code> should be declared using the <code>var</code> keyword");'
|
||||
- text: <code>oopsGlobal</code> debe ser una variable global y tener un valor de <code>5</code>
|
||||
testString: 'assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5, "<code>oopsGlobal</code> should be a global variable and have a value of <code>5</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Declare your variable here
|
||||
|
||||
|
||||
function fun1() {
|
||||
// Assign 5 to oopsGlobal Here
|
||||
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if (typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if (typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### Before Test
|
||||
<div id='js-setup'>
|
||||
|
||||
```js
|
||||
var logOutput = "";
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
logOutput = message;
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
var oopsGlobal;
|
||||
capture();
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
// Declare your variable here
|
||||
var myGlobal = 10;
|
||||
|
||||
function fun1() {
|
||||
// Assign 5 to oopsGlobal Here
|
||||
oopsGlobal = 5;
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if(typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if(typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c0
|
||||
title: Global vs. Local Scope in Functions
|
||||
localeTitle: Ámbito global vs. local en funciones
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Es posible tener variables <dfn>locales</dfn> y <dfn>globales</dfn> con el mismo nombre. Cuando haces esto, la variable <code>local</code> tiene prioridad sobre la variable <code>global</code> .
|
||||
En este ejemplo:
|
||||
<blockquote>var someVar = "Hat";<br>function myFun() {<br> var someVar = "Head";<br> return someVar;<br>}</blockquote>
|
||||
La función <code>myFun</code> devolverá <code>"Head"</code> porque la versión <code>local</code> de la variable está presente.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Agregue una variable local a la función <code>myOutfit</code> para anular el valor de <code>outerWear</code> con <code>"sweater"</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: No cambie el valor de la <code>outerWear</code> global
|
||||
testString: 'assert(outerWear === "T-Shirt", "Do not change the value of the global <code>outerWear</code>");'
|
||||
- text: <code>myOutfit</code> debe devolver <code>"sweater"</code>
|
||||
testString: 'assert(myOutfit() === "sweater", "<code>myOutfit</code> should return <code>"sweater"</code>");'
|
||||
- text: No cambie la declaración de devolución
|
||||
testString: 'assert(/return outerWear/.test(code), "Do not change the return statement");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var outerWear = "T-Shirt";
|
||||
|
||||
function myOutfit() {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return outerWear;
|
||||
}
|
||||
|
||||
myOutfit();
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var outerWear = "T-Shirt";
|
||||
function myOutfit() {
|
||||
var outerWear = "sweater";
|
||||
return outerWear;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 5664820f61c48e80c9fa476c
|
||||
title: Golf Code
|
||||
localeTitle: Codigo de golf
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
En el juego de <a href="https://en.wikipedia.org/wiki/Golf" target="_blank">golf,</a> cada hoyo tiene un <code>par</code> significa el número promedio de <code>strokes</code> que se espera que un golfista realice para hundir la bola en un hoyo para completar el juego. Dependiendo de qué tan por encima o <code>par</code> debajo de tus <code>strokes</code> , hay un apodo diferente.
|
||||
Su función se pasará <code>par</code> y <code>strokes</code> argumentos. Devuelva la cadena correcta de acuerdo con esta tabla que enumera los trazos en orden de prioridad; arriba (más alto) a abajo (más bajo):
|
||||
<table class="table table-striped"><thead><tr><th> Trazos </th><th> Regreso </th></tr></thead><tbody><tr><td> 1 </td><td> "¡Hoyo en uno!" </td></tr><tr><td> <= par - 2 </td><td> "Águila" </td></tr><tr><td> par - 1 </td><td> "Pajarito" </td></tr><tr><td> par </td><td> "Par" </td></tr><tr><td> par + 1 </td><td> "Espectro" </td></tr><tr><td> par + 2 </td><td> "Doble Bogey" </td></tr><tr><td> > = par + 3 </td><td> "¡Vete a casa!" </td></tr></tbody></table>
|
||||
<code>par</code> y <code>strokes</code> siempre serán numéricos y positivos. Hemos agregado una matriz de todos los nombres para su conveniencia.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>golfScore(4, 1)</code> debe devolver "Hole-in-one!"'
|
||||
testString: 'assert(golfScore(4, 1) === "Hole-in-one!", "<code>golfScore(4, 1)</code> should return "Hole-in-one!"");'
|
||||
- text: ' <code>golfScore(4, 2)</code> debe devolver "Eagle"'
|
||||
testString: 'assert(golfScore(4, 2) === "Eagle", "<code>golfScore(4, 2)</code> should return "Eagle"");'
|
||||
- text: ' <code>golfScore(5, 2)</code> debe devolver "Eagle"'
|
||||
testString: 'assert(golfScore(5, 2) === "Eagle", "<code>golfScore(5, 2)</code> should return "Eagle"");'
|
||||
- text: ' <code>golfScore(4, 3)</code> debe devolver "Birdie"'
|
||||
testString: 'assert(golfScore(4, 3) === "Birdie", "<code>golfScore(4, 3)</code> should return "Birdie"");'
|
||||
- text: ' <code>golfScore(4, 4)</code> debe devolver "Par"
|
||||
testString: 'assert(golfScore(4, 4) === "Par", "<code>golfScore(4, 4)</code> should return "Par"");'
|
||||
- text: ' <code>golfScore(1, 1)</code> debe devolver "Hole-in-one!"'
|
||||
testString: 'assert(golfScore(1, 1) === "Hole-in-one!", "<code>golfScore(1, 1)</code> should return "Hole-in-one!"");'
|
||||
- text: ' <code>golfScore(5, 5)</code> debe devolver "Par"
|
||||
testString: 'assert(golfScore(5, 5) === "Par", "<code>golfScore(5, 5)</code> should return "Par"");'
|
||||
- text: ' <code>golfScore(4, 5)</code> debería devolver "Bogey"'
|
||||
testString: 'assert(golfScore(4, 5) === "Bogey", "<code>golfScore(4, 5)</code> should return "Bogey"");'
|
||||
- text: ' <code>golfScore(4, 6)</code> debería devolver "Double Bogey"'
|
||||
testString: 'assert(golfScore(4, 6) === "Double Bogey", "<code>golfScore(4, 6)</code> should return "Double Bogey"");'
|
||||
- text: ' <code>golfScore(4, 7)</code> debe devolver "Go Home!"'
|
||||
testString: 'assert(golfScore(4, 7) === "Go Home!", "<code>golfScore(4, 7)</code> should return "Go Home!"");'
|
||||
- text: ' <code>golfScore(5, 9)</code> debe devolver "Go Home!"'
|
||||
testString: 'assert(golfScore(5, 9) === "Go Home!", "<code>golfScore(5, 9)</code> should return "Go Home!"");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
|
||||
function golfScore(par, strokes) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
// Change these values to test
|
||||
golfScore(5, 4);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function golfScore(par, strokes) {
|
||||
if (strokes === 1) {
|
||||
return "Hole-in-one!";
|
||||
}
|
||||
|
||||
if (strokes <= par - 2) {
|
||||
return "Eagle";
|
||||
}
|
||||
|
||||
if (strokes === par - 1) {
|
||||
return "Birdie";
|
||||
}
|
||||
|
||||
if (strokes === par) {
|
||||
return "Par";
|
||||
}
|
||||
|
||||
if (strokes === par + 1) {
|
||||
return "Bogey";
|
||||
}
|
||||
|
||||
if(strokes === par + 2) {
|
||||
return "Double Bogey";
|
||||
}
|
||||
|
||||
return "Go Home!";
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ac
|
||||
title: Increment a Number with JavaScript
|
||||
localeTitle: Incrementar un número con JavaScript
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Puede <dfn>incrementar</dfn> o agregar fácilmente uno a una variable con el operador <code>++</code> .
|
||||
<code>i++;</code>
|
||||
es el equivalente de
|
||||
<code>i = i + 1;</code>
|
||||
<strong>Nota</strong> <br> La línea entera se convierte en <code>i++;</code> , eliminando la necesidad del signo igual.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambie el código para usar el operador <code>++</code> en <code>myVar</code> .
|
||||
<strong>Pista</strong> <br> Obtenga más información sobre los <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()" target="_blank">operadores aritméticos - Incremento (++)</a> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>myVar</code> debe ser igual a <code>88</code>
|
||||
testString: 'assert(myVar === 88, "<code>myVar</code> should equal <code>88</code>");'
|
||||
- text: <code>myVar = myVar + 1;</code> debería ser cambiado
|
||||
testString: 'assert(/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code), "<code>myVar = myVar + 1;</code> should be changed");'
|
||||
- text: Usa el operador <code>++</code>
|
||||
testString: 'assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code), "Use the <code>++</code> operator");'
|
||||
- text: No cambie el código por encima de la línea
|
||||
testString: 'assert(/var myVar = 87;/.test(code), "Do not change code above the line");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar + 1;
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
myVar++;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a9
|
||||
title: Initializing Variables with the Assignment Operator
|
||||
localeTitle: Inicializando variables con el operador de asignación
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Es común <dfn>inicializar</dfn> una variable a un valor inicial en la misma línea que se declara.
|
||||
<code>var myVar = 0;</code>
|
||||
Crea una nueva variable llamada <code>myVar</code> y le asigna un valor inicial de <code>0</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Defina una variable <code>a</code> con <code>var</code> e inicialícela a un valor de <code>9</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Inicializar <code>a</code> a un valor de <code>9</code>
|
||||
testString: 'assert(/var\s+a\s*=\s*9\s*/.test(code), "Initialize <code>a</code> to a value of <code>9</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourVar = 19;
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var a = 9;
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244db
|
||||
title: Introducing Else If Statements
|
||||
localeTitle: Introduciendo Else If Sentencias
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Si tiene varias condiciones que deben abordarse, puede encadenar <code>if</code> sentencias junto con <code>else if</code> sent.
|
||||
<blockquote>if (num > 15) {<br> return "Bigger than 15";<br>} else if (num < 5) {<br> return "Smaller than 5";<br>} else {<br> return "Between 5 and 15";<br>}</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Convertir la lógica para usar <code>else if</code> instrucciones.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Debes tener al menos dos declaraciones <code>else</code>
|
||||
testString: 'assert(code.match(/else/g).length > 1, "You should have at least two <code>else</code> statements");'
|
||||
- text: Debes tener al menos dos declaraciones <code>if</code>
|
||||
testString: 'assert(code.match(/if/g).length > 1, "You should have at least two <code>if</code> statements");'
|
||||
- text: Usted debe tener que cerrar y abrir llaves para cada condición
|
||||
testString: 'assert(code.match(/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/), "You should have closing and opening curly braces for each condition in your if else statement");'
|
||||
- text: <code>testElseIf(0)</code> debería devolver "Más pequeño que 5"
|
||||
testString: 'assert(testElseIf(0) === "Smaller than 5", "<code>testElseIf(0)</code> should return "Smaller than 5"");'
|
||||
- text: <code>testElseIf(5)</code> debe devolver "Entre 5 y 10"
|
||||
testString: 'assert(testElseIf(5) === "Between 5 and 10", "<code>testElseIf(5)</code> should return "Between 5 and 10"");'
|
||||
- text: <code>testElseIf(7)</code> debe devolver "Entre 5 y 10"
|
||||
testString: 'assert(testElseIf(7) === "Between 5 and 10", "<code>testElseIf(7)</code> should return "Between 5 and 10"");'
|
||||
- text: <code>testElseIf(10)</code> debe devolver "Entre 5 y 10"
|
||||
testString: 'assert(testElseIf(10) === "Between 5 and 10", "<code>testElseIf(10)</code> should return "Between 5 and 10"");'
|
||||
- text: <code>testElseIf(12)</code> debe devolver "Más de 10"
|
||||
testString: 'assert(testElseIf(12) === "Greater than 10", "<code>testElseIf(12)</code> should return "Greater than 10"");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if (val > 10) {
|
||||
return "Greater than 10";
|
||||
}
|
||||
|
||||
if (val < 5) {
|
||||
return "Smaller than 5";
|
||||
}
|
||||
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testElseIf(7);
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if(val > 10) {
|
||||
return "Greater than 10";
|
||||
} else if(val < 5) {
|
||||
return "Smaller than 5";
|
||||
} else {
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,92 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244da
|
||||
title: Introducing Else Statements
|
||||
localeTitle: Introduciendo otras declaraciones
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Cuando una condición para una sentencia <code>if</code> es verdadera, se ejecuta el bloque de código siguiente. ¿Qué pasa cuando esa condición es falsa? Normalmente no pasaría nada. Con una sentencia <code>else</code> , se puede ejecutar un bloque de código alternativo.
|
||||
<blockquote>if (num > 10) {<br> return "Bigger than 10";<br>} else {<br> return "10 or Less";<br>}</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Combine las sentencias <code>if</code> en una sola sentencia <code>if/else</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Solo debes tener una sentencia <code>if</code> en el editor.
|
||||
testString: 'assert(code.match(/if/g).length === 1, "You should only have one <code>if</code> statement in the editor");'
|
||||
- text: Debes usar una sentencia <code>else</code>
|
||||
testString: 'assert(/else/g.test(code), "You should use an <code>else</code> statement");'
|
||||
- text: <code>testElse(4)</code> debe devolver "5 o más pequeño"
|
||||
testString: 'assert(testElse(4) === "5 or Smaller", "<code>testElse(4)</code> should return "5 or Smaller"");'
|
||||
- text: <code>testElse(5)</code> debe devolver "5 o más pequeño"
|
||||
testString: 'assert(testElse(5) === "5 or Smaller", "<code>testElse(5)</code> should return "5 or Smaller"");'
|
||||
- text: <code>testElse(6)</code> debe devolver "Más grande que 5"
|
||||
testString: 'assert(testElse(6) === "Bigger than 5", "<code>testElse(6)</code> should return "Bigger than 5"");'
|
||||
- text: <code>testElse(10)</code> debe devolver "Más grande que 5"
|
||||
testString: 'assert(testElse(10) === "Bigger than 5", "<code>testElse(10)</code> should return "Bigger than 5"");'
|
||||
- text: No cambie el código por encima o por debajo de las líneas.
|
||||
testString: 'assert(/var result = "";/.test(code) && /return result;/.test(code), "Do not change the code above or below the lines.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
// Only change code below this line
|
||||
|
||||
if (val > 5) {
|
||||
result = "Bigger than 5";
|
||||
}
|
||||
|
||||
if (val <= 5) {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return result;
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
testElse(4);
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
if(val > 5) {
|
||||
result = "Bigger than 5";
|
||||
} else {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 56104e9e514f539506016a5c
|
||||
title: Iterate Odd Numbers With a For Loop
|
||||
localeTitle: Iterar números impares con un bucle for
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Para que los bucles no tengan que iterar uno a la vez. Al cambiar nuestra <code>final-expression</code> , podemos contar por números pares.
|
||||
Comenzaremos en <code>i = 0</code> y haremos un bucle mientras que <code>i < 10</code> . Incrementaremos <code>i</code> en 2 en cada bucle con <code>i += 2</code> .
|
||||
<blockquote>var ourArray = [];<br>for (var i = 0; i < 10; i += 2) {<br> ourArray.push(i);<br>}</blockquote>
|
||||
<code>ourArray</code> ahora contendrá <code>[0,2,4,6,8]</code> .
|
||||
Cambiemos nuestra <code>initialization</code> para que podamos contar por números impares.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Empuje los números impares del 1 al 9 a <code>myArray</code> usando un bucle <code>for</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Usted debe estar usando una <code>for</code> bucle para esto.
|
||||
testString: 'assert(code.match(/for\s*\(/g).length > 1, "You should be using a <code>for</code> loop for this.");'
|
||||
- text: ' <code>myArray</code> debería ser igual a <code>[1,3,5,7,9]</code> .'
|
||||
testString: 'assert.deepEqual(myArray, [1,3,5,7,9], "<code>myArray</code> should equal <code>[1,3,5,7,9]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourArray = [];
|
||||
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 10; i += 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,94 @@
|
||||
---
|
||||
id: 5675e877dbd60be8ad28edc6
|
||||
title: Iterate Through an Array with a For Loop
|
||||
localeTitle: Iterar a través de una matriz con un bucle For
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Una tarea común en JavaScript es iterar a través del contenido de una matriz. Una forma de hacerlo es con un bucle <code>for</code> . Este código dará salida a cada elemento de la matriz <code>arr</code> a la consola:
|
||||
<blockquote>var arr = [10,9,8,7,6];<br>for (var i = 0; i < arr.length; i++) {<br> console.log(arr[i]);<br>}</blockquote>
|
||||
Recuerde que las matrices tienen numeración basada en cero, lo que significa que el último índice de la matriz es la longitud - 1. Nuestra <dfn>condición</dfn> para este bucle es <code>i < arr.length</code> , que se detiene cuando <code>i</code> tiene la longitud - 1.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Declarar e inicializar una variable <code>total</code> a <code>0</code> . Use un bucle <code>for</code> para agregar el valor de cada elemento de la matriz <code>myArr</code> al <code>total</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>total</code> debe ser declarado e inicializado a 0
|
||||
testString: 'assert(code.match(/var.*?total\s*=\s*0.*?;/), "<code>total</code> should be declared and initialized to 0");'
|
||||
- text: <code>total</code> debe ser igual a 20
|
||||
testString: 'assert(total === 20, "<code>total</code> should equal 20");'
|
||||
- text: Debe usar un bucle <code>for</code> para iterar a través de <code>myArr</code>
|
||||
testString: 'assert(code.match(/for\s*\(/g).length > 1 && code.match(/myArr\s*\[/), "You should use a <code>for</code> loop to iterate through <code>myArr</code>");'
|
||||
- text: No establezca el <code>total</code> a 20 directamente
|
||||
testString: 'assert(!code.match(/total[\s\+\-]*=\s*(\d(?!\s*[;,])|[1-9])/g), "Do not set <code>total</code> to 20 directly");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourArr = [ 9, 10, 11, 12];
|
||||
var ourTotal = 0;
|
||||
|
||||
for (var i = 0; i < ourArr.length; i++) {
|
||||
ourTotal += ourArr[i];
|
||||
}
|
||||
|
||||
// Setup
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var ourArr = [ 9, 10, 11, 12];
|
||||
var ourTotal = 0;
|
||||
|
||||
for (var i = 0; i < ourArr.length; i++) {
|
||||
ourTotal += ourArr[i];
|
||||
}
|
||||
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
var total = 0;
|
||||
|
||||
for (var i = 0; i < myArr.length; i++) {
|
||||
total += myArr[i];
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 5a2efd662fb457916e1fe604
|
||||
title: Iterate with JavaScript Do...While Loops
|
||||
localeTitle: Iterar con JavaScript Do ... While Loops
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Puede ejecutar el mismo código varias veces utilizando un bucle.
|
||||
El siguiente tipo de bucle que aprenderá se llama bucle " <code>do...while</code> " porque primero " <code>do</code> " una pasada del código dentro del bucle sin importar qué, y luego se ejecuta " <code>while</code> " una condición específica es verdadero y se detiene una vez que esa condición ya no es verdadera. Veamos un ejemplo.
|
||||
<blockquote>var ourArray = [];<br>var i = 0;<br>do {<br> ourArray.push(i);<br> i++;<br>} while (i < 5);</blockquote>
|
||||
Esto se comporta como se esperaría con cualquier otro tipo de bucle, y la matriz resultante se verá como <code>[0, 1, 2, 3, 4]</code> . Sin embargo, lo que hace <code>do...while</code> diferente de otros bucles es cómo se comporta cuando la condición falla en la primera comprobación. Veamos esto en acción.
|
||||
Aquí hay un bucle while común que ejecutará el código en el bucle siempre y cuando <code>i < 5</code> .
|
||||
<blockquote>var ourArray = []; <br>var i = 5;<br>while (i < 5) {<br> ourArray.push(i);<br> i++;<br>}</blockquote>
|
||||
Observe que inicializamos el valor de <code>i</code> en 5. Cuando ejecutamos la siguiente línea, notamos que <code>i</code> no es menor que 5. Por lo tanto, no ejecutamos el código dentro del bucle. El resultado es que <code>ourArray</code> no agregará nada, por lo que aún se verá así <code>[]</code> cuando todo el código del ejemplo anterior termine de ejecutarse.
|
||||
Ahora, eche un vistazo a un <code>do...while</code> loop.
|
||||
<blockquote>var ourArray = []; <br>var i = 5;<br>do {<br> ourArray.push(i);<br> i++;<br>} while (i < 5);</blockquote>
|
||||
En este caso, inicializamos el valor de <code>i</code> como 5, como hicimos con el bucle while. Cuando llegamos a la siguiente línea, no hay comprobación del valor de <code>i</code> , por lo que vamos al código dentro de las llaves y lo ejecutamos. Agregaremos un elemento a la matriz e incrementaremos <code>i</code> antes de llegar a la verificación de condición. Entonces, cuando se llega a comprobar si <code>i < 5</code> ver que <code>i</code> es ahora de 6 años, que no pasa la comprobación condicional. Así que salimos del bucle y estamos listos. Al final del ejemplo anterior, el valor de <code>ourArray</code> es <code>[5]</code> .
|
||||
Esencialmente, un bucle <code>do...while</code> while garantiza que el código dentro del bucle se ejecute al menos una vez.
|
||||
Intentemos obtener un ciclo <code>do...while</code> while para que funcione presionando los valores en una matriz.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambiar el <code>while</code> de bucle en el código a un <code>do...while</code> bucle de modo que el bucle empujará el número 10 a <code>myArray</code> , y <code>i</code> será igual a <code>11</code> cuando el código termina de ejecutarse.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Deberías usar un bucle <code>do...while</code> while para esto.
|
||||
testString: 'assert(code.match(/do/g), "You should be using a <code>do...while</code> loop for this.");'
|
||||
- text: ' <code>myArray</code> debería ser igual a <code>[10]</code> '.
|
||||
testString: 'assert.deepEqual(myArray, [10], "<code>myArray</code> should equal <code>[10]</code>.");'
|
||||
- text: <code>i</code> debe ser igual a <code>11</code>
|
||||
testString: 'assert.deepEqual(i, 11, "<code>i</code> should equal <code>11</code>");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
while (i < 5) {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
do {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
} while (i < 5)
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb5bdef
|
||||
title: Iterate with JavaScript For Loops
|
||||
localeTitle: Iterar con JavaScript para bucles
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Puede ejecutar el mismo código varias veces utilizando un bucle.
|
||||
El tipo más común de bucle de JavaScript se llama " <code>for loop</code> " porque se ejecuta "por" un número específico de veces.
|
||||
Para los bucles se declaran con tres expresiones opcionales separadas por punto y coma:
|
||||
<code>for ([initialization]; [condition]; [final-expression])</code>
|
||||
La instrucción de <code>initialization</code> se ejecuta una sola vez antes de que comience el bucle. Normalmente se utiliza para definir y configurar su variable de bucle.
|
||||
La declaración de <code>condition</code> se evalúa al comienzo de cada iteración de bucle y continuará mientras se evalúe como <code>true</code> . Cuando la <code>condition</code> es <code>false</code> al inicio de la iteración, el bucle dejará de ejecutarse. Esto significa que si la <code>condition</code> comienza como <code>false</code> , su bucle nunca se ejecutará.
|
||||
La <code>final-expression</code> se ejecuta al final de cada iteración de bucle, antes de la siguiente verificación de <code>condition</code> y generalmente se usa para aumentar o disminuir su contador de bucle.
|
||||
En el siguiente ejemplo, inicializamos con <code>i = 0</code> e iteramos mientras nuestra condición <code>i < 5</code> es verdadera. Incrementaremos <code>i</code> en <code>1</code> en cada iteración de bucle con <code>i++</code> como nuestra <code>final-expression</code> .
|
||||
<blockquote>var ourArray = [];<br>for (var i = 0; i < 5; i++) {<br> ourArray.push(i);<br>}</blockquote>
|
||||
<code>ourArray</code> ahora contendrá <code>[0,1,2,3,4]</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use un bucle <code>for</code> para trabajar y empujar los valores del 1 al 5 en <code>myArray</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Usted debe estar usando una <code>for</code> bucle para esto.
|
||||
testString: 'assert(code.match(/for\s*\(/g).length > 1, "You should be using a <code>for</code> loop for this.");'
|
||||
- text: ' <code>myArray</code> debe ser igual a <code>[1,2,3,4,5]</code> .'
|
||||
testString: 'assert.deepEqual(myArray, [1,2,3,4,5], "<code>myArray</code> should equal <code>[1,2,3,4,5]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourArray = [];
|
||||
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 6; i++) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb1bdef
|
||||
title: Iterate with JavaScript While Loops
|
||||
localeTitle: Iterar con JavaScript mientras bucles
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Puede ejecutar el mismo código varias veces utilizando un bucle.
|
||||
El primer tipo de bucle vamos a aprender se llama un " <code>while</code> " bucle porque funciona "mientras que" una condición especificada es verdadera y se detiene una vez que la condición ya no es cierto.
|
||||
<blockquote>var ourArray = [];<br>var i = 0;<br>while(i < 5) {<br> ourArray.push(i);<br> i++;<br>}</blockquote>
|
||||
Intentemos que funcione un bucle while empujando los valores a una matriz.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Empuje los números de 0 a 4 para <code>myArray</code> usando un <code>while</code> de bucle.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Usted debe utilizar un <code>while</code> de bucle para esto.
|
||||
testString: 'assert(code.match(/while/g), "You should be using a <code>while</code> loop for this.");'
|
||||
- text: ' <code>myArray</code> debe ser igual a <code>[0,1,2,3,4]</code> .'
|
||||
testString: 'assert.deepEqual(myArray, [0,1,2,3,4], "<code>myArray</code> should equal <code>[0,1,2,3,4]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 0;
|
||||
while(i < 5) {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,111 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bf
|
||||
title: Local Scope and Functions
|
||||
localeTitle: Ámbito local y funciones
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Las variables que se declaran dentro de una función, así como los parámetros de la función tienen alcance <dfn>local</dfn> . Eso significa que, sólo son visibles dentro de esa función.
|
||||
Aquí hay una función <code>myTest</code> con una variable local llamada <code>loc</code> .
|
||||
<blockquote>function myTest() {<br> var loc = "foo";<br> console.log(loc);<br>}<br>myTest(); // logs "foo"<br>console.log(loc); // loc is not defined</blockquote>
|
||||
<code>loc</code> no está definido fuera de la función.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Declare una variable local <code>myVar</code> dentro de <code>myLocalScope</code> . Ejecute las pruebas y luego siga las instrucciones comentadas en el editor.
|
||||
<strong>Pista</strong> <br> Actualizar la página puede ayudar si te quedas atascado.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Ninguna variable global <code>myVar</code>
|
||||
testString: 'assert(typeof myVar === "undefined", "No global <code>myVar</code> variable");'
|
||||
- text: Agrega una variable <code>myVar</code> local
|
||||
testString: 'assert(/var\s+myVar/.test(code), "Add a local <code>myVar</code> variable");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
'use strict'; // you shouldn't need to edit this line
|
||||
|
||||
console.log(myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
|
||||
// Run and check the console
|
||||
// myVar is not defined outside of myLocalScope
|
||||
console.log(myVar);
|
||||
|
||||
// Now remove the console log line to pass the test
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### Before Test
|
||||
<div id='js-setup'>
|
||||
|
||||
```js
|
||||
var logOutput = "";
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
logOutput = message;
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
'use strict';
|
||||
|
||||
var myVar;
|
||||
console.log(myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 5690307fddb111c6084545d7
|
||||
title: Logical Order in If Else Statements
|
||||
localeTitle: Orden lógico en si otras declaraciones
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
orden es importante en <code>if</code> , <code>else if</code> declaraciones.
|
||||
La función se ejecuta de arriba a abajo, por lo que deberá tener cuidado con la afirmación que aparece primero.
|
||||
Toma estas dos funciones como ejemplo.
|
||||
Aquí está el primero:
|
||||
<blockquote>function foo(x) {<br> if (x < 1) {<br> return "Less than one";<br> } else if (x < 2) {<br> return "Less than two";<br> } else {<br> return "Greater than or equal to two";<br> }<br>}</blockquote>
|
||||
Y el segundo solo cambia el orden de las declaraciones:
|
||||
<blockquote>function bar(x) {<br> if (x < 2) {<br> return "Less than two";<br> } else if (x < 1) {<br> return "Less than one";<br> } else {<br> return "Greater than or equal to two";<br> }<br>}</blockquote>
|
||||
Si bien estas dos funciones parecen casi idénticas, si pasamos un número a ambas obtenemos diferentes salidas.
|
||||
<blockquote>foo(0) // "Less than one"<br>bar(0) // "Less than two"</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambie el orden de la lógica en la función para que devuelva las declaraciones correctas en todos los casos.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>orderMyLogic(4)</code> debe devolver "Menos de 5"
|
||||
testString: 'assert(orderMyLogic(4) === "Less than 5", "<code>orderMyLogic(4)</code> should return "Less than 5"");'
|
||||
- text: <code>orderMyLogic(6)</code> debe devolver "Menos de 10"
|
||||
testString: 'assert(orderMyLogic(6) === "Less than 10", "<code>orderMyLogic(6)</code> should return "Less than 10"");'
|
||||
- text: <code>orderMyLogic(11)</code> debe devolver "Mayor o igual a 10"
|
||||
testString: 'assert(orderMyLogic(11) === "Greater than or equal to 10", "<code>orderMyLogic(11)</code> should return "Greater than or equal to 10"");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function orderMyLogic(val) {
|
||||
if (val < 10) {
|
||||
return "Less than 10";
|
||||
} else if (val < 5) {
|
||||
return "Less than 5";
|
||||
} else {
|
||||
return "Greater than or equal to 10";
|
||||
}
|
||||
}
|
||||
|
||||
// Change this value to test
|
||||
orderMyLogic(7);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
function orderMyLogic(val) {
|
||||
if(val < 5) {
|
||||
return "Less than 5";
|
||||
} else if (val < 10) {
|
||||
return "Less than 10";
|
||||
} else {
|
||||
return "Greater than or equal to 10";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cc
|
||||
title: Manipulate Arrays With pop()
|
||||
localeTitle: Manipular matrices con pop ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Otra forma de cambiar los datos en una matriz es con la función <code>.pop()</code> .
|
||||
<code>.pop()</code> se usa para " <code>.pop()</code> " un valor del final de una matriz. Podemos almacenar este valor "extraído" asignándolo a una variable. En otras palabras, <code>.pop()</code> elimina el último elemento de una matriz y devuelve ese elemento.
|
||||
Cualquier tipo de entrada se puede "extraer" de una matriz: números, cadenas, incluso matrices anidadas.
|
||||
<blockquote> <code>var threeArr = [1, 4, 6];<br> var oneDown = threeArr.pop();<br> console.log(oneDown); // Returns 6<br> console.log(threeArr); // Returns [1, 4]</code> </blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use la función <code>.pop()</code> para eliminar el último elemento de <code>myArray</code> , asignando el valor de "desprendimiento de" a <code>removedFromMyArray</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>myArray</code> solo debe contener <code>[["John", 23]]</code> .'
|
||||
testString: 'assert((function(d){if(d[0][0] == "John" && d[0][1] === 23 && d[1] == undefined){return true;}else{return false;}})(myArray), "<code>myArray</code> should only contain <code>[["John", 23]]</code>.");'
|
||||
- text: Usa <code>pop()</code> en <code>myArray</code>
|
||||
testString: 'assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code), "Use <code>pop()</code> on <code>myArray</code>");'
|
||||
- text: ' <code>removedFromMyArray</code> solo debe contener <code>["cat", 2]</code> .'
|
||||
testString: 'assert((function(d){if(d[0] == "cat" && d[1] === 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), "<code>removedFromMyArray</code> should only contain <code>["cat", 2]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourArray = [1,2,3];
|
||||
var removedFromOurArray = ourArray.pop();
|
||||
// removedFromOurArray now equals 3, and ourArray now equals [1,2]
|
||||
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line.
|
||||
var removedFromMyArray;
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
var removedFromMyArray = myArray.pop();
|
||||
```
|
||||
|
||||
</section>
|
@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cb
|
||||
title: Manipulate Arrays With push()
|
||||
localeTitle: Manipular matrices con empuje ()
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Una forma fácil de agregar datos al final de una matriz es a través de la función <code>push()</code> .
|
||||
<code>.push()</code> toma uno o más <dfn>parámetros</dfn> y los "empuja" al final de la matriz.
|
||||
<blockquote>var arr = [1,2,3];<br>arr.push(4);<br>// arr is now [1,2,3,4]</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Presione <code>["dog", 3]</code> en el extremo de la variable <code>myArray</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>myArray</code> ahora debe ser igual a <code>[["John", 23], ["cat", 2], ["dog", 3]]</code> .'
|
||||
testString: 'assert((function(d){if(d[2] != undefined && d[0][0] == "John" && d[0][1] === 23 && d[2][0] == "dog" && d[2][1] === 3 && d[2].length == 2){return true;}else{return false;}})(myArray), "<code>myArray</code> should now equal <code>[["John", 23], ["cat", 2], ["dog", 3]]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// Example
|
||||
var ourArray = ["Stimpson", "J", "cat"];
|
||||
ourArray.push(["happy", "joy"]);
|
||||
// ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]]
|
||||
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line.
|
||||
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
### After Test
|
||||
<div id='js-teardown'>
|
||||
|
||||
```js
|
||||
console.info('after the test');
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
myArray.push(["dog",3]);
|
||||
```
|
||||
|
||||
</section>
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user