chore(i8n,curriculum): processed translations (#41504)
Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a661e0f1068aca922b3ef17
|
||||
title: Access an Array's Contents Using Bracket Notation
|
||||
title: Accede a los contenidos de un arreglo utilizando la notación de corchetes
|
||||
challengeType: 1
|
||||
forumTopicId: 301149
|
||||
dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
@ -8,55 +8,55 @@ dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
|
||||
La principal característica de cualquier estructura de datos es, por supuesto, la habilidad no solo de guardar datos, sino también de ser capaz de recuperar esos datos cuando le es requerido. Entonces, ahora que hemos aprendido como crear un arreglo, comencemos a pensar en cómo podemos acceder a la información de ese arreglo.
|
||||
|
||||
When we define a simple array as seen below, there are 3 items in it:
|
||||
Cuando definimos un arreglo simple como el que se ve a continuación, hay 3 elementos en él:
|
||||
|
||||
```js
|
||||
let ourArray = ["a", "b", "c"];
|
||||
```
|
||||
|
||||
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the ***zeroth*** position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>. For example, if we want to retrieve the `"a"` from `ourArray` and assign it to a variable, we can do so with the following code:
|
||||
En un arreglo, cada elemento tiene un <dfn>índice</dfn>. Este índice funciona como la posición de ese elemento en el arreglo y es como puedes referenciarlo. Sin embargo, es importante tener en cuenta, que los arreglos en JavaScript son <dfn>indexados en base cero</dfn>, es decir que el primer elemento de un arreglo está en la posición ***cero***, no en la uno. Para recuperar un elemento de un arreglo podemos encerrar un índice entre corchetes y agregarlo al final de este, o más comúnmente, a una variable que hace referencia a un objeto tipo arreglo. Esto es conocido como <dfn>notación de corchetes</dfn>. Por ejemplo, si queremos recuperar la `a` de `ourArray` y asignársela a una variable, podemos hacerlo con el siguiente código:
|
||||
|
||||
```js
|
||||
let ourVariable = ourArray[0];
|
||||
// ourVariable equals "a"
|
||||
```
|
||||
|
||||
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
|
||||
Ahora `ourVariable` tiene el valor de `a`.
|
||||
|
||||
Además de acceder al valor asociado con un índice, también puedes *establecer* un índice a un valor usando la misma notación:
|
||||
|
||||
```js
|
||||
ourArray[1] = "not b anymore";
|
||||
// ourArray now equals ["a", "not b anymore", "c"];
|
||||
```
|
||||
|
||||
Using bracket notation, we have now reset the item at index 1 from `"b"`, to `"not b anymore"`.
|
||||
Utilizando la notación de corchetes, ahora hemos restablecido el elemento en el índice 1 de la cadena `b`, a `not b anymore`. Ahora `ourArray` es `["a", "not b anymore", "c"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides `"b"`.
|
||||
Para completar este desafío, establece la segunda posición (índice `1`) de `myArray` a cualquier cosa que quieras, además de la letra `b`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray[0]` should be equal to `"a"`
|
||||
`myArray[0]` debe ser igual a la letra `a`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[0], 'a');
|
||||
```
|
||||
|
||||
`myArray[1]` should not be equal to `"b"`
|
||||
`myArray[1]` no debe ser igual a la letra `b`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(myArray[1], 'b');
|
||||
```
|
||||
|
||||
`myArray[2]` should be equal to `"c"`
|
||||
`myArray[2]`debe ser igual a la letra `c`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[2], 'c');
|
||||
```
|
||||
|
||||
`myArray[3]` should be equal to `"d"`
|
||||
`myArray[3]` debe ser igual a la letra `d`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[3], 'd');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0e
|
||||
title: Add Items to an Array with push() and unshift()
|
||||
title: Agrega elementos a un arreglo con push() y unshift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301151
|
||||
dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
@ -8,28 +8,32 @@ dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
|
||||
# --description--
|
||||
|
||||
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: `Array.push()` and `Array.unshift()`.
|
||||
La longitud de un arreglo, así como los tipos de datos que puede contener, no es fija. Los arreglos pueden ser definidos con la cantidad de elementos que se desee, y dichos elementos pueden ser agregados o removidos con el tiempo; en otras palabras, los arreglos son <dfn>mutables</dfn>. En este desafío, veremos dos métodos con los que podemos modificar un arreglo: `Array.push()` y `Array.unshift()`.
|
||||
|
||||
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the `push()` method adds elements to the end of an array, and `unshift()` adds elements to the beginning. Consider the following:
|
||||
Ambos métodos toman uno o más elementos como parámetros y los agregan al arreglo que hizo la llamada; el método `push()` agrega los elementos al final del arreglo, mientras que `unshift()` los agrega al inicio. Considera lo siguiente:
|
||||
|
||||
```js
|
||||
let twentyThree = 'XXIII';
|
||||
let romanNumerals = ['XXI', 'XXII'];
|
||||
|
||||
romanNumerals.unshift('XIX', 'XX');
|
||||
// now equals ['XIX', 'XX', 'XXI', 'XXII']
|
||||
|
||||
romanNumerals.push(twentyThree);
|
||||
// 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.
|
||||
```
|
||||
|
||||
`romanNumerals` tendrá el valor `['XIX', 'XX', 'XXI', 'XXII']`.
|
||||
|
||||
```js
|
||||
romanNumerals.push(twentyThree);
|
||||
```
|
||||
|
||||
`romanNumerals` tendrá el valor `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`. Ten en cuenta que también podemos pasar variables, que nos permiten una mayor flexibilidad en la modificación dinámica de los datos de nuestro arreglo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `mixedNumbers`, which we are passing an array as an argument. Modify the function by using `push()` and `unshift()` to add `'I', 2, 'three'` to the beginning of the array and `7, 'VIII', 9` to the end so that the returned array contains representations of the numbers 1-9 in order.
|
||||
Hemos definido una función, `mixedNumbers`, a la cual le estamos pasando un arreglo como argumento. Modifica la función utilizando `push()` y `unshift()` para agregar `'I', 2, 'three'` al principio del arreglo y `7, 'VIII', 9` al final, de tal modo que el arreglo devuelto contenga las representaciones de los números del 1 al 9 en orden.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mixedNumbers(["IV", 5, "six"])` should now return `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
|
||||
`mixedNumbers(["IV", 5, "six"])` ahora debe devolver `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
@ -45,13 +49,13 @@ assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
]);
|
||||
```
|
||||
|
||||
The `mixedNumbers` function should utilize the `push()` method
|
||||
La función `mixedNumbers` debe utilizar el método `push()`
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.push/));
|
||||
```
|
||||
|
||||
The `mixedNumbers` function should utilize the `unshift()` method
|
||||
La función `mixedNumbers` debe utilizar el método `unshift()`
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.unshift/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b3367417b2b2512b11
|
||||
title: Add Items Using splice()
|
||||
title: Agrega elementos usando splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301152
|
||||
dashedName: add-items-using-splice
|
||||
@ -8,7 +8,7 @@ dashedName: add-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
|
||||
¿Recuerdas que en el último desafío mencionamos que `splice()` puede tomar hasta tres parámetros? Pues bien, puedes usar el tercer parámetro, compuesto por uno o varios elementos, para agregarlo al arreglo. Esto puede ser increíblemente útil para cambiar rápidamente un elemento, o un conjunto de elementos, por otro.
|
||||
|
||||
```js
|
||||
const numbers = [10, 11, 12, 12, 15];
|
||||
@ -16,20 +16,20 @@ const startIndex = 3;
|
||||
const amountToDelete = 1;
|
||||
|
||||
numbers.splice(startIndex, amountToDelete, 13, 14);
|
||||
// the second entry of 12 is removed, and we add 13 and 14 at the same index
|
||||
console.log(numbers);
|
||||
// returns [ 10, 11, 12, 13, 14, 15 ]
|
||||
```
|
||||
|
||||
Here, we begin with an array of numbers. Then, we pass the following to `splice()`: The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
|
||||
La segunda entrada de `12` es removida, y agregamos `13` y `14` en el mismo índice. El arreglo `numbers` ahora será `[ 10, 11, 12, 13, 14, 15 ]`.
|
||||
|
||||
Aquí, comenzamos con un arreglo de números. A continuación, pasamos lo siguiente a `splice()`: El índice en el que empezar a borrar elementos (3), el número de elementos a borrar (1), y el resto de argumentos (13, 14) se insertarán a partir de ese mismo índice. Ten en cuenta que puede haber cualquier número de elementos (separados por comas) después de `amountToDelete`, cada uno de los cuales es insertado.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
|
||||
Hemos definido una función, `htmlColorNames`, que toma un arreglo de colores HTML como argumento. Modifica la función usando `splice()` para eliminar los dos primeros elementos del arreglo y agrega `'DarkSalmon'` y `'BlanchedAlmond'` en sus respectivos lugares.
|
||||
|
||||
# --hints--
|
||||
|
||||
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
|
||||
`htmlColorNames` debe devolver `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -50,19 +50,19 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
The `htmlColorNames` function should utilize the `splice()` method
|
||||
La función `htmlColorNames` debe utilizar el método `splice()`
|
||||
|
||||
```js
|
||||
assert(/.splice/.test(code));
|
||||
```
|
||||
|
||||
You should not use `shift()` or `unshift()`.
|
||||
No debes usar `shift()` o `unshift()`.
|
||||
|
||||
```js
|
||||
assert(!/shift|unshift/.test(code));
|
||||
```
|
||||
|
||||
You should not use array bracket notation.
|
||||
No debes usar notación de corchetes.
|
||||
|
||||
```js
|
||||
assert(!/\[\d\]\s*=/.test(code));
|
||||
|
@ -63,19 +63,19 @@ Se ha creado un objeto `foods` con tres entradas. Usando la sintaxis de tu elecc
|
||||
assert(typeof foods === 'object');
|
||||
```
|
||||
|
||||
El objeto `foods` debe tener una clave `"bananas"` con el valor de `13`.
|
||||
El objeto `foods` debe tener una clave `bananas` con el valor de `13`.
|
||||
|
||||
```js
|
||||
assert(foods.bananas === 13);
|
||||
```
|
||||
|
||||
El objeto `foods` debe tener una clave `"grapes"` con el valor de `35`.
|
||||
El objeto `foods` debe tener una clave `grapes` con el valor de `35`.
|
||||
|
||||
```js
|
||||
assert(foods.grapes === 35);
|
||||
```
|
||||
|
||||
El objeto `foods` debe tener una clave `"strawberries"` con el valor de `27`.
|
||||
El objeto `foods` debe tener una clave `strawberries` con el valor de `27`.
|
||||
|
||||
```js
|
||||
assert(foods.strawberries === 27);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b14
|
||||
title: Comprobar la presencia de un elemento con indexOf()
|
||||
title: Comprueba la presencia de un elemento con indexOf()
|
||||
challengeType: 1
|
||||
forumTopicId: 301154
|
||||
dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
@ -15,18 +15,20 @@ Por ejemplo:
|
||||
```js
|
||||
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
|
||||
|
||||
fruits.indexOf('dates'); // returns -1
|
||||
fruits.indexOf('oranges'); // returns 2
|
||||
fruits.indexOf('pears'); // returns 1, the first index at which the element exists
|
||||
fruits.indexOf('dates');
|
||||
fruits.indexOf('oranges');
|
||||
fruits.indexOf('pears');
|
||||
```
|
||||
|
||||
`indexOf('dates')` devuelve `-1`, `indexOf('oranges')` devuelve `2`, e `indexOf('pears')` devuelve `1` (el primer índice en el que existe cada elemento).
|
||||
|
||||
# --instructions--
|
||||
|
||||
`indexOf()` puede ser increíblemente útil para comprobar rápidamente la presencia de un elemento en un arreglo. Hemos definido una función, `quickCheck`, que toma un arreglo y un elemento como argumentos. Modifica la función usando `indexOf()` para que devuelva `true` si el elemento pasado existe en el arreglo, y `false` si no existe.
|
||||
`indexOf()` puede ser increíblemente útil para verificar rápidamente la presencia de un elemento en un arreglo. Hemos definido una función, `quickCheck`, que toma un arreglo y un elemento como argumentos. Modifica la función usando `indexOf()` para que devuelva `true` si el elemento pasado existe en el arreglo, y `false` si no existe.
|
||||
|
||||
# --hints--
|
||||
|
||||
La función `quickCheck` debe devolver un booleano (`true` o `false`), no una cadena (`"true"` o `"false"`)
|
||||
La función `quickCheck` debe devolver un valor booleano (`true` o `false`), no una cadena (`"true"` o `"false"`)
|
||||
|
||||
```js
|
||||
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
|
@ -13,12 +13,13 @@ Ahora podemos agregar, modificar y eliminar claves de los objetos. Pero, ¿y si
|
||||
```js
|
||||
users.hasOwnProperty('Alan');
|
||||
'Alan' in users;
|
||||
// both return true
|
||||
```
|
||||
|
||||
Ambos devuelven `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Hemos creado un objeto, `users`, con algunos usuarios en él y una función `isEveryoneHere`, a la que pasamos el objeto `users` como argumento. Termina de escribir esta función para que devuelva `true` sólo si el objeto `users` contiene los cuatro nombres, `Alan`, `Jeff`, `Sarah` y `Ryan`, como claves, y `false` en caso contrario.
|
||||
Hemos creado un objeto, `users`, con algunos usuarios en él y una función `isEveryoneHere`, a la que pasamos el objeto `users` como argumento. Termina de escribir esta función para que devuelva `true` solo si el objeto `users` contiene los cuatro nombres, `Alan`, `Jeff`, `Sarah` y `Ryan`, como claves, y `false`en caso contrario.
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -34,13 +35,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
La función `isEveryoneHere` debe devolver `true` si `Alan`, `Jeff`, `Sarah`, y `Ryan` son propiedades en el objeto `users`
|
||||
La función `isEveryoneHere` debe devolver `true` si `Alan`, `Jeff`, `Sarah`, y `Ryan` son propiedades del objeto `users`
|
||||
|
||||
```js
|
||||
assert(isEveryoneHere(users) === true);
|
||||
```
|
||||
|
||||
La función `isEveryoneHere` debe devolver `false` si `Alan` no es una propiedad en el objeto `users`
|
||||
La función `isEveryoneHere` debe devolver `false` si `Alan` no es una propiedad del objeto `users`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -51,7 +52,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
La función `isEveryoneHere` debe devolver `false` si `Jeff` no es una propiedad en el objeto `users`
|
||||
La función `isEveryoneHere` debe devolver `false` si `Jeff` no es una propiedad del objeto `users`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -62,7 +63,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
La función `isEveryoneHere` debe devolver `false` si `Sarah` no es una propiedad en el objeto `users`
|
||||
La función `isEveryoneHere` debe devolver `false` si `Sarah` no es una propiedad del objeto `users`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -73,7 +74,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
La función `isEveryoneHere` debe devolver `false` si `Ryan` no es una propiedad en el objeto `users`
|
||||
La función `isEveryoneHere` debe devolver `false` si `Ryan` no es una propiedad del objeto `users`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b17
|
||||
title: Combine Arrays with the Spread Operator
|
||||
title: Combina arreglos con el operador de propagación
|
||||
challengeType: 1
|
||||
forumTopicId: 301156
|
||||
dashedName: combine-arrays-with-the-spread-operator
|
||||
@ -8,30 +8,31 @@ dashedName: combine-arrays-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
Another huge advantage of the <dfn>spread</dfn> operator, is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
|
||||
Otra gran ventaja del operador de <dfn>propagació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 arreglos, pero esto sólo nos permite combinar arreglos al final de uno, y al principio de otro. La sintaxis de propagación hace la siguiente operación extremadamente simple:
|
||||
|
||||
```js
|
||||
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
|
||||
|
||||
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
|
||||
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
|
||||
```
|
||||
|
||||
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
|
||||
`thatArray` tendrá el valor `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`.
|
||||
|
||||
Usando la sintaxis de propagación, acabamos de lograr una operación que habría sido más compleja y verbosa si hubiéramos usado métodos tradicionales.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
|
||||
Hemos definido una función `spreadOut` que devuelve la variable `sentence`. Modifica la función usando el operador de <dfn>propagación</dfn> para que devuelva el arreglo `['learning', 'to', 'code', 'is', 'fun']`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
|
||||
`spreadOut` debe devolver `["learning", "to", "code", "is", "fun"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
|
||||
```
|
||||
|
||||
The `spreadOut` function should utilize spread syntax
|
||||
La función `spreadOut` debe utilizar la sintaxis de propagación
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b13
|
||||
title: Copy an Array with the Spread Operator
|
||||
title: Copia un arreglo con el operador de propagación
|
||||
challengeType: 1
|
||||
forumTopicId: 301157
|
||||
dashedName: copy-an-array-with-the-spread-operator
|
||||
@ -8,24 +8,24 @@ dashedName: copy-an-array-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
While `slice()` allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
|
||||
Mientras que `slice()` nos permite ser selectivos sobre qué elementos de un arreglo copiar, entre otras tareas útiles, el nuevo <dfn>operador de propagación</dfn> de ES6 nos permite copiar fácilmente *todos* los elementos de una arreglo, en orden, con una sintaxis simple y altamente legible. La sintaxis de propagación simplemente se ve así: `...`
|
||||
|
||||
In practice, we can use the spread operator to copy an array like so:
|
||||
En la práctica, podemos utilizar el operador de propagación para copiar un arreglo de esta manera:
|
||||
|
||||
```js
|
||||
let thisArray = [true, true, undefined, false, null];
|
||||
let thatArray = [...thisArray];
|
||||
// thatArray equals [true, true, undefined, false, null]
|
||||
// thisArray remains unchanged and thatArray contains the same elements as thisArray
|
||||
```
|
||||
|
||||
`thatArray` es igual a `[true, true, undefined, false, null]`. `thisArray` permanece sin cambios y `thatArray` contiene los mismos elementos que `thisArray`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
|
||||
Hemos definido una función, `copyMachine` que toma `arr` (un arreglo) y `num` (un número) como argumentos. Se supone que la función devuelve un nuevo arreglo compuesto por `num` copias de `arr`. Hemos hecho la mayor parte del trabajo por ti, pero aún no funciona del todo bien. Modifica la función usando sintaxis de propagación para que funcione correctamente (sugerencia: ¡otro método que ya hemos cubierto podría ser útil aquí!).
|
||||
|
||||
# --hints--
|
||||
|
||||
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
|
||||
`copyMachine([true, false, true], 2)` debe devolver `[[true, false, true], [true, false, true]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
@ -34,7 +34,7 @@ assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
|
||||
`copyMachine([1, 2, 3], 5)` debe devolver `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
@ -46,13 +46,13 @@ assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
|
||||
`copyMachine([true, true, null], 1)` debe devolver `[[true, true, null]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
|
||||
```
|
||||
|
||||
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
|
||||
`copyMachine(["it works"], 3)` debe devolver `[["it works"], ["it works"], ["it works"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
@ -62,7 +62,7 @@ assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
The `copyMachine` function should utilize the `spread operator` with array `arr`
|
||||
La función `copyMachine` debe utilizar el `spread operator` (operador de propagación) con el arreglo `arr`
|
||||
|
||||
```js
|
||||
assert(__helpers.removeJSComments(code).match(/\.\.\.arr/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7a367417b2b2512b12
|
||||
title: Copy Array Items Using slice()
|
||||
title: Copia elementos de un arreglo usando slice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301158
|
||||
dashedName: copy-array-items-using-slice
|
||||
@ -8,25 +8,25 @@ dashedName: copy-array-items-using-slice
|
||||
|
||||
# --description--
|
||||
|
||||
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
|
||||
El siguiente método que cubriremos es `slice()`. En lugar de modificar un arreglo, `slice()` copia o *extrae* un número determinado de elementos a un nuevo arreglo, dejando intacto el arreglo al que se llama. `slice()` toma sólo 2 parámetros: el primero es el índice en el que se inicia la extracción, y el segundo es el índice en el que se detiene la extracción (la extracción se producirá hasta el índice, pero sin incluir el elemento en este índice). Considera esto:
|
||||
|
||||
```js
|
||||
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
|
||||
|
||||
let todaysWeather = weatherConditions.slice(1, 3);
|
||||
// todaysWeather equals ['snow', 'sleet'];
|
||||
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
|
||||
```
|
||||
|
||||
In effect, we have created a new array by extracting elements from an existing array.
|
||||
`todaysWeather` tendrá el valor `['snow', 'sleet']`, mientras que `weatherConditions` todavía tendrá `['rain', 'snow', 'sleet', 'hail', 'clear']`.
|
||||
|
||||
En efecto, hemos creado un nuevo arreglo extrayendo elementos de un arreglo existente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the elements `'warm'` and `'sunny'`.
|
||||
Hemos definido una función, `forecast`, que toma un arreglo como argumento. Modifica la función usando `slice()` para extraer información del arreglo de argumentos y devuelve un nuevo arreglo que contenga los elementos `warm` y `sunny`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`forecast` should return `["warm", "sunny"]`
|
||||
`forecast` debe devolver `["warm", "sunny"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -35,7 +35,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
The `forecast` function should utilize the `slice()` method
|
||||
La función `forecast` debe utilizar el método `slice()`
|
||||
|
||||
```js
|
||||
assert(/\.slice\(/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b16
|
||||
title: Crear arreglos complejos multidimensionales
|
||||
title: Crea arreglos complejos multidimensionales
|
||||
challengeType: 1
|
||||
forumTopicId: 301159
|
||||
dashedName: create-complex-multi-dimensional-arrays
|
||||
@ -13,43 +13,45 @@ dashedName: create-complex-multi-dimensional-arrays
|
||||
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 formados por otros arreglos. Hemos visto arreglos que contienen arreglos en desafíos anteriores, pero bastante simples. Sin embargo, los arreglos pueden contener una profundidad infinita de arreglos que pueden contener otros arreglos, cada uno con sus propios niveles arbitrarios de profundidad, y así sucesivamente. De esta manera, un arreglo puede convertirse rápidamente en una estructura de datos muy compleja, conocida como <dfn>multidimensional</dfn>, o arreglo anidado. Considera el siguiente ejemplo:
|
||||
|
||||
```js
|
||||
let nestedArray = [ // top, or first level - the outer most array
|
||||
['deep'], // an array within an array, 2 levels of depth
|
||||
let nestedArray = [
|
||||
['deep'],
|
||||
[
|
||||
['deeper'], ['deeper'] // 2 arrays nested 3 levels deep
|
||||
['deeper'], ['deeper']
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest'], ['deepest'] // 2 arrays nested 4 levels deep
|
||||
['deepest'], ['deepest']
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest-est?'] // an array nested 5 levels deep
|
||||
['deepest-est?']
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
```
|
||||
|
||||
Aunque este ejemplo pueda parecer enrevesado, este nivel de complejidad no es inaudito, ni siquiera inusual, cuando se trata de grandes cantidades de datos. Sin embargo, podemos acceder muy fácilmente a los niveles más profundos de un arreglo tan complejo con la notación de corchetes:
|
||||
El arreglo `deep` está anidado a 2 niveles de profundidad. El arreglo `deeper` está a 3 niveles de profundidad. Los arreglos `deepest` están anidados a 4 niveles y el arreglo `deepest-est?` a 5.
|
||||
|
||||
Si bien este ejemplo puede parecer complicado, este nivel de complejidad no es desconocido, ni siquiera inusual, cuando se trata de grandes cantidades de datos. Sin embargo, todavía podemos acceder muy fácilmente a los niveles más profundos de un arreglo tan complejo con notación de corchetes:
|
||||
|
||||
```js
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
// logs: deepest-est?
|
||||
```
|
||||
|
||||
Y ahora que sabemos dónde está ese dato, podemos restablecerlo si lo necesitamos:
|
||||
Esto registra la cadena `deepest-est?`. Y ahora que sabemos dónde está ese dato, podemos restablecerlo si es necesario:
|
||||
|
||||
```js
|
||||
nestedArray[2][1][0][0][0] = 'deeper still';
|
||||
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
// now logs: deeper still
|
||||
```
|
||||
|
||||
Ahora registra `deeper still`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Hemos definido una variable, `myNestedArray`, como un arreglo. Modifica `myNestedArray`, utilizando cualquier combinación de <dfn>cadenas</dfn>, <dfn>números</dfn> y <dfn>booleanos</dfn> para los elementos de datos, de modo que tenga exactamente cinco niveles de profundidad (recuerda que el arreglo más externo es el nivel 1). En algún lugar del tercer nivel, incluye la cadena `'deep'`, en el cuarto nivel, incluye la cadena `'deeper'`, y en el quinto nivel, incluye la cadena `'deepest'`.
|
||||
Hemos definido una variable, `myNestedArray`, como un arreglo. Modifica `myNestedArray`, utilizando cualquier combinación de <dfn>cadenas</dfn>, <dfn>números</dfn> y <dfn>booleanos</dfn> para los elementos de datos, de modo que tenga exactamente cinco niveles de profundidad (recuerda que el arreglo más externo es el nivel 1). En algún lugar del tercer nivel, incluye la cadena `deep`, en el cuarto nivel, incluye la cadena `deeper` y en el quinto nivel, incluye la cadena `deepest`.
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -100,7 +102,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` debe contener exactamente una aparición de la cadena `"deep"` en un arreglo anidado a 3 niveles de profundidad
|
||||
`myNestedArray` debe contener exactamente una aparición de la cadena `deep` en un arreglo anidado a 3 niveles de profundidad
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -129,7 +131,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` debe contener exactamente una aparición de la cadena `"deeper"` en un arreglo anidado a 4 niveles de profundidad
|
||||
`myNestedArray` debe contener exactamente una aparición de la cadena `deeper` en un arreglo anidado a 4 niveles de profundidad
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -158,7 +160,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` debe contener exactamente una aparición de la cadena `"deepest"` en un arreglo anidado a 5 niveles de profundidad
|
||||
`myNestedArray` debe contener exactamente una aparición de la cadena `deepest` en un arreglo anidado a 5 niveles de profundidad
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b15
|
||||
title: Iterate Through All an Array's Items Using For Loops
|
||||
title: Itera a través de todos los elementos de un arreglo utilizando bucles "for"
|
||||
challengeType: 1
|
||||
forumTopicId: 301161
|
||||
dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
@ -8,9 +8,9 @@ dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
|
||||
A veces, cuando se trabaja con arreglos, es muy útil poder iterar a través de cada elemento para encontrar uno o más elementos que podamos necesitar, o manipular un arreglo en función de los elementos de datos que cumplen un determinado conjunto de criterios. JavaScript ofrece varios métodos incorporados que iteran sobre arreglos de formas ligeramente diferentes para conseguir distintos resultados (como `every()`, `forEach()`, `map()`, etc.), sin embargo, la técnica que es más flexible y nos ofrece la mayor cantidad de control es un simple bucle `for`.
|
||||
|
||||
Consider the following:
|
||||
Considera lo siguiente:
|
||||
|
||||
```js
|
||||
function greaterThanTen(arr) {
|
||||
@ -24,18 +24,17 @@ function greaterThanTen(arr) {
|
||||
}
|
||||
|
||||
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
|
||||
// returns [12, 14, 80]
|
||||
```
|
||||
|
||||
Using a `for` loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than `10`, and returned a new array containing those items.
|
||||
Usando un bucle `for`, esta función itera y accede a cada elemento del arreglo, y lo somete a una simple prueba que hemos creado. De esta manera, hemos determinado de forma sencilla y programática qué elementos de datos son mayores que `10`, y hemos devuelto un nuevo arreglo, `[12, 14, 80]`, que contiene esos elementos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
|
||||
Hemos definido una función, `filteredArray`, que toma `arr`, un arreglo anidado, y `elem` como argumentos, y devuelve un nuevo arreglo. `elem` representa un elemento que puede o no estar presente en uno o más de los arreglos anidados dentro de `arr`. Modifica la función, usando un bucle `for`, para que devuelva una versión filtrada del arreglo pasado de forma que cualquier arreglo anidado dentro de `arr` que contenga `elem` haya sido eliminado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[ [10, 8, 3], [14, 6, 23] ]`
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` debe devolver `[[10, 8, 3], [14, 6, 23]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -54,7 +53,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` should return `[ ["flutes", 4] ]`
|
||||
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` debe devolver `[["flutes", 4]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -70,7 +69,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` should return `[ ["amy", "beth", "sam"] ]`
|
||||
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` debe devolver `[["amy", "beth", "sam"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -85,7 +84,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[ ]`
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` debe devolver `[]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -102,7 +101,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
The `filteredArray` function should utilize a `for` loop
|
||||
La función `filteredArray` debe utilizar un bucle `for`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1d
|
||||
title: Iterate Through the Keys of an Object with a for...in Statement
|
||||
title: Itera a través de las claves de un objeto con una sentencia "for...in"
|
||||
challengeType: 1
|
||||
forumTopicId: 301162
|
||||
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
@ -8,25 +8,23 @@ dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our `users` object, this could look like:
|
||||
A veces es necesario iterar por todas las claves de un objeto. Esto requiere una sintaxis específica en JavaScript llamada sentencia <dfn>for...in</dfn>. Para nuestro objeto `users`, esto podría verse así:
|
||||
|
||||
```js
|
||||
for (let user in users) {
|
||||
console.log(user);
|
||||
}
|
||||
|
||||
// logs:
|
||||
Alan
|
||||
Jeff
|
||||
Sarah
|
||||
Ryan
|
||||
```
|
||||
|
||||
In this statement, we defined a variable `user`, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console. **NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
|
||||
Esto registrará `Alan`, `Jeff`, `Sarah`, y `Ryan`, cada valor en su propia línea.
|
||||
|
||||
En esta sentencia, definimos una variable `user`, y como puedes ver, esta variable se restablece durante cada iteración a cada una de las claves del objeto a medida que la sentencia hace un bucle a través del objeto, dando como resultado que el nombre de cada usuario se imprima en la consola.
|
||||
|
||||
**NOTA:** Los objetos no mantienen un orden para las claves almacenadas como lo hacen los arreglos; por lo tanto, la posición de una clave en un objeto, o el orden relativo en el que aparece, es irrelevante cuando se hace referencia o se accede a esa clave.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
|
||||
Hemos definido una función `countOnline` que acepta un argumento (un objeto usuario). Utiliza una sentencia <dfn>for...in</dfn> dentro de esta función para iterar sobre el objeto usuarios (users) pasado a la función y devuelve el número de usuarios cuya propiedad `online` esté establecida como `true`. A continuación se muestra un ejemplo de un objeto usuario que podría pasarse a `countOnline`. Cada usuario tendrá una propiedad `online` con un valor `true` o `false`.
|
||||
|
||||
```js
|
||||
{
|
||||
@ -44,7 +42,7 @@ We've defined a function `countOnline` which accepts one argument (a users objec
|
||||
|
||||
# --hints--
|
||||
|
||||
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
|
||||
La función `countOnline` debe utilizar una sentencia `for in` para iterar por las claves del objeto que se le pasa.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,19 +52,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
|
||||
La función `countOnline` debe devolver `1` cuando se le pasa el objeto `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }`
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj1) === 1);
|
||||
```
|
||||
|
||||
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
|
||||
La función `countOnline` debe devolver `2` cuando se le pasa el objeto `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }`
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj2) === 2);
|
||||
```
|
||||
|
||||
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
|
||||
La función `countOnline` debe devolver `0` cuando se le pasa el objeto `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }`
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj3) === 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0f
|
||||
title: Remove Items from an Array with pop() and shift()
|
||||
title: Elimina elementos de un arreglo con pop() y shift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301165
|
||||
dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
@ -8,35 +8,39 @@ dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
|
||||
# --description--
|
||||
|
||||
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
|
||||
Tanto `push()` como `unshift()` tienen métodos correspondientes que son casi opuestos funcionales: `pop()` y `shift()`. Como ya habrás adivinado, en lugar de agregar, `pop()` *elimina* un elemento al final de un arreglo, mientras que `shift()` elimina un elemento al principio. La diferencia clave entre `pop()` y `shift()` y sus primos `push()` y `unshift()`, es que ninguno de los dos métodos toma parámetros, y cada uno sólo permite modificar un arreglo por un solo elemento a la vez.
|
||||
|
||||
Let's take a look:
|
||||
Echemos un vistazo:
|
||||
|
||||
```js
|
||||
let greetings = ['whats up?', 'hello', 'see ya!'];
|
||||
|
||||
greetings.pop();
|
||||
// now equals ['whats up?', 'hello']
|
||||
|
||||
greetings.shift();
|
||||
// now equals ['hello']
|
||||
```
|
||||
|
||||
We can also return the value of the removed element with either method like this:
|
||||
`greetings` tendrá el valor `['whats up?', 'hello']`.
|
||||
|
||||
```js
|
||||
greetings.shift();
|
||||
```
|
||||
|
||||
`greetings` tendrá el valor `['hello']`.
|
||||
|
||||
También podemos devolver el valor del elemento eliminado con cualquiera de los dos métodos así:
|
||||
|
||||
```js
|
||||
let popped = greetings.pop();
|
||||
// returns 'hello'
|
||||
// greetings now equals []
|
||||
```
|
||||
|
||||
`greetings` tendrá el valor `[]` y `popped` tendría el valor `hello`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
|
||||
Hemos definido una función, `popShift`, el cual toma un arreglo como argumento y devuelve un nuevo arreglo. Modifica la función, usando `pop()` y `shift()`, para eliminar el primer y el último elemento del arreglo, y asignar los elementos eliminados a sus correspondientes variables, de modo que el arreglo que se devuelva contenga sus valores.
|
||||
|
||||
# --hints--
|
||||
|
||||
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
|
||||
`popShift(["challenge", "is", "not", "complete"])` debe devolver `["challenge", "complete"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
@ -45,13 +49,13 @@ assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
]);
|
||||
```
|
||||
|
||||
The `popShift` function should utilize the `pop()` method
|
||||
La función `popShift` debe utilizar el método `pop()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
|
||||
```
|
||||
|
||||
The `popShift` function should utilize the `shift()` method
|
||||
La función `popShift` debe utilizar el método `shift()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b10
|
||||
title: Remove Items Using splice()
|
||||
title: Elimina elementos usando splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301166
|
||||
dashedName: remove-items-using-splice
|
||||
@ -8,34 +8,35 @@ dashedName: remove-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
|
||||
Bien, ya hemos aprendido a eliminar elementos al principio y al final de los arreglos utilizando `shift()` y `pop()`, pero ¿qué pasa si queremos eliminar un elemento de alguna parte del medio? ¿O eliminar más de un elemento a la vez? Pues bien, ahí es donde entra `splice()`. `splice()` nos permite hacer precisamente eso: **eliminar cualquier número de elementos consecutivos** de cualquier parte de un arreglo.
|
||||
|
||||
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
|
||||
`splice()` puede tomar hasta 3 parámetros, pero por ahora, nos centraremos sólo en los 2 primeros. Los dos primeros parámetros de `splice()` son enteros que representan índices, o posiciones, del arreglo que llama `splice()`. Y recuerda que los arreglos están *indexados en cero*, por lo que para indicar el primer elemento de un arreglo, usaríamos `0`. El primer parámetro de `splice()` representa el índice del arreglo a partir del cual se empiezan a eliminar los elementos, mientras que el segundo parámetro indica el número de elementos a eliminar. Por ejemplo:
|
||||
|
||||
```js
|
||||
let array = ['today', 'was', 'not', 'so', 'great'];
|
||||
|
||||
array.splice(2, 2);
|
||||
// remove 2 elements beginning with the 3rd element
|
||||
// array now equals ['today', 'was', 'great']
|
||||
```
|
||||
|
||||
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
|
||||
Aquí eliminamos 2 elementos, comenzando con el tercer elemento (en el índice 2). `array` tendrá el valor `['today', 'was', 'great']`.
|
||||
|
||||
`splice()` no sólo modifica el arreglo que llama, sino que también devuelve un nuevo arreglo que contiene el valor de los elementos eliminados:
|
||||
|
||||
```js
|
||||
let array = ['I', 'am', 'feeling', 'really', 'happy'];
|
||||
|
||||
let newArray = array.splice(3, 2);
|
||||
// newArray equals ['really', 'happy']
|
||||
```
|
||||
|
||||
`newArray` tiene el valor `['really', 'happy']`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
|
||||
Hemos inicializado un arreglo `arr`. Usa `splice()` para eliminar elementos de `arr`, de forma que sólo contenga elementos que sumen el valor de `10`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
|
||||
No debes cambiar la línea original de `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,7 +44,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`arr` should only contain elements that sum to `10`.
|
||||
`arr` sólo debe contener elementos que sumen `10`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -52,13 +53,13 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should utilize the `splice()` method on `arr`.
|
||||
Tu código debe utilizar el método `splice()` en `arr`.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
|
||||
```
|
||||
|
||||
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
|
||||
La división (splice) sólo debe eliminar elementos de `arr` y no agregar ningún elemento adicional a `arr`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b20
|
||||
title: Use an Array to Store a Collection of Data
|
||||
title: Utiliza un arreglo para almacenar una colección de datos
|
||||
challengeType: 1
|
||||
forumTopicId: 301167
|
||||
dashedName: use-an-array-to-store-a-collection-of-data
|
||||
@ -8,15 +8,16 @@ dashedName: use-an-array-to-store-a-collection-of-data
|
||||
|
||||
# --description--
|
||||
|
||||
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
|
||||
Lo siguiente es un ejemplo de la implementación más simple de una estructura de datos de un arreglo. Esto se conoce como un <dfn>arreglo unidimensional</dfn>, lo que significa que sólo tiene un nivel, o que no tiene otros arreglos anidados dentro de él. Observa que contiene <dfn>booleanos</dfn>, <dfn>cadenas</dfn> y <dfn>números</dfn>, entre otros tipos de datos válidos de JavaScript:
|
||||
|
||||
```js
|
||||
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
|
||||
console.log(simpleArray.length);
|
||||
// logs 7
|
||||
```
|
||||
|
||||
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
|
||||
La llamada `console.log` muestra `7`.
|
||||
|
||||
Todos los arreglos tienen una propiedad de longitud, que como se muestra arriba, se puede acceder muy fácilmente con la sintaxis `Array.length`. A continuación se puede ver una implementación más compleja de un arreglo. Esto se conoce como un <dfn>arreglo multidimensional</dfn>, o un arreglo que contiene otros arreglos. Observa que este arreglo también contiene <dfn>objetos</dfn> JavaScript, que examinaremos muy de cerca en la siguiente sección, pero por ahora, todo lo que necesitas saber es que los arreglos también son capaces de almacenar objetos complejos.
|
||||
|
||||
```js
|
||||
let complexArray = [
|
||||
@ -45,35 +46,35 @@ let complexArray = [
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
|
||||
Hemos definido una variable llamada `yourArray`. Completa la sentencia asignando un arreglo de al menos 5 elementos de longitud a la variable `yourArray`. Tu arreglo debe contener al menos una <dfn>cadena</dfn> (string), un <dfn>número</dfn> (number) y un <dfn>booleano</dfn> (boolean).
|
||||
|
||||
# --hints--
|
||||
|
||||
`yourArray` should be an array.
|
||||
`yourArray` debe ser un arreglo.
|
||||
|
||||
```js
|
||||
assert.strictEqual(Array.isArray(yourArray), true);
|
||||
```
|
||||
|
||||
`yourArray` should be at least 5 elements long.
|
||||
`yourArray` debe tener al menos 5 elementos de largo.
|
||||
|
||||
```js
|
||||
assert.isAtLeast(yourArray.length, 5);
|
||||
```
|
||||
|
||||
`yourArray` should contain at least one `boolean`.
|
||||
`yourArray` debe contener al menos un `boolean`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` should contain at least one `number`.
|
||||
`yourArray` debe contener al menos un `number`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` should contain at least one `string`.
|
||||
`yourArray` debe contener al menos un `string`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
|
||||
|
Reference in New Issue
Block a user