{ "name": "Object Oriented and Functional Programming", "order": 7, "time": "2 hours", "helpRoom": "HelpJavaScript", "note": [ "Methods", "Closures", "Factories", "Pure Functions", "Currying Functions", "Functors", "Currying Functions" ], "challenges": [ { "id": "cf1111c1c15feddfaeb1bdef", "title": "Declare JavaScript Objects as Variables", "description": [ "Before we dive into Object Oriented Programming, let's revisit JavaScript objects.", "Give your motorBike object a wheels, engines and seats attribute and set them to numbers." ], "challengeSeed": [ "var car = {", " \"wheels\":4,", " \"engines\":1,", " \"seats\":5", "};", "", "var motorBike = {", "", " // Only change code below this line.", "", "};" ], "tail": [ "(function() {return JSON.stringify(motorBike);})();" ], "solutions": [ "var car = {\n \"wheels\":4,\n \"engines\":1,\n \"seats\":5\n};\n\nvar motorBike = {\n \"wheels\": 4,\n \"engines\": 1,\n \"seats\": 2\n};" ], "tests": [ "assert(typeof motorBike.engines === 'number', 'message: motorBike should have a engines attribute set to a number.');", "assert(typeof motorBike.wheels === 'number', 'message: motorBike should have a wheels attribute set to a number.');", "assert(typeof motorBike.seats === 'number', 'message: motorBike should have a seats attribute set to a number.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Declara objetos de JavaScript como variables", "descriptionEs": [ "Antes de sumergirnos en Programación Orientada a Objetos, vamos a revisar los objetos de JavaScript.", "Dale a tu objeto motorBike un atributo wheels, otro llamado motors y otro seats y asignales números." ] }, { "id": "cf1111c1c15feddfaeb2bdef", "title": "Construct JavaScript Objects with Functions", "description": [ "We are also able to create objects using constructor functions.", "A constructor function is given a capitalized name to make it clear that it is a constructor.", "Here's an example of a constructor function:", "
var Car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 1;
};
", "In a constructor the this variable refers to the new object being created by the constructor. So when we write,", "  this.wheels = 4;", "inside of the constructor we are giving the new object it creates a property called wheels with a value of 4.", "You can think of a constructor as a description for the object it will create.", "Have your MotorBike constructor describe an object with wheels, engines and seats properties and set them to numbers." ], "challengeSeed": [ "var Car = function() {", " this.wheels = 4;", " this.engines = 1;", " this.seats = 1;", "};", "", "// Only change code below this line.", "", "var MotorBike = function() {", "", "};" ], "tail": [ "(function() {return JSON.stringify(new MotorBike());})();" ], "solutions": [ "var Car = function() {\n this.wheels = 4;\n this.engines = 1;\n this.seats = 1;\n};\n\nvar myCar = new Car();\n\nvar MotorBike = function() {\n this.engines = 1;\n this.seats = 1;\n this.wheels = 4;\n};\n\nvar myMotorBike = new MotorBike();" ], "tests": [ "assert(typeof (new MotorBike()).engines === 'number', 'message: MotorBike should have a engines attribute set to a number.');", "assert(typeof (new MotorBike()).wheels === 'number', 'message: MotorBike should have a wheels attribute set to a number.');", "assert(typeof (new MotorBike()).seats === 'number', 'message: MotorBike should have a seats attribute set to a number.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Construye objetos de JavaScript con funciones", "descriptionEs": [ "También podemos crear objetos utilizando funciones constructoras.", "A cada función constructora se le da un nombre comenzando en mayúsculas para que quede claro que es una constructora.", "He aquí un ejemplo de una función constructora:", "var Carro = function() {", "& nbsp; & nbsp; this.llantas = 4; ", "& nbsp; & nbsp; this.motores = 1; ", "& nbsp; & nbsp; this.asientos = 1; ", "}; ", "En una constructora la variable this hace referencia al nuevo objeto que está siendo creado por la constructora. Así que cuando escribimos ", "  this.llantas = 4;", "dentro de la constructora le estamos dando el nuevo objeto que se crea una propiedad llamada llantas con un valor de 4.", "Puedes pensar en una constructora como una descripción del objeto que crea.", "Haz que tu constructora MotorBike describa un objeto con las propiedades wheels,engines and seats y asignales números." ] }, { "id": "cf1111c1c15feddfaeb4bdef", "title": "Make Instances of Objects with a Constructor Function", "description": [ "Now let's put that great constructor function we made in the last lesson to use!", "To use a constructor function we call it with the new keyword in front of it like:", "var myCar = new Car();", "myCar is now an instance of the Car constructor that looks like the object it described:", "
{
  wheels: 4,
  engines: 1,
  seats: 1
}
", "Note that it is important to use the new keyword when calling a constructor. This is how Javascript knows to create a new object and that all the references to this inside the constructor should be referring to this new object.", "Now, once the myCar instance is created it can be used like any other object and can have its properties accessed and modified the same way you would usually. For example:", "myCar.turboType = \"twin\";", "Our myCar variable now has a property turboType with a value of \"twin\".", "In the editor, use the Car constructor to create a new instance and assign it to myCar.", "Then give myCar a nickname property with a string value." ], "challengeSeed": [ "var Car = function() {", " this.wheels = 4;", " this.engines = 1;", " this.seats = 1;", "};", "", "// Only change code below this line.", "", "var myCar;" ], "tail": [ "(function() {return JSON.stringify(myCar);})();" ], "solutions": [ "var Car = function() {\n this.wheels = 4;\n this.engines = 1;\n this.seats = 1;\n};\n\nvar myCar = new Car();\n\nmyCar.nickname = \"Lucy\";" ], "tests": [ "assert((new Car()).wheels === 4, 'message: The property wheels should still be 4 in the object constructor.');", "assert(typeof (new Car()).nickname === 'undefined', 'message: There should not be a property nickname in the object constructor.');", "assert(myCar.wheels === 4, 'message: The property wheels of myCar should equal 4.');", "assert(typeof myCar.nickname === 'string', 'message: The property nickname of myCar should be a string.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Crea instancias de objetos con funciones constructoras", "descriptionEs": [ "¡Ahora usemos esa gran constructora que hicimos en la última lección!", "Para utilizar una función constructora la llamamos con la palabra reservada new al frente, como:", "var miCarro = new Carro();", "miCarroes ahora una instancia de la constructora Carro que se parece al objeto que describe:", "{", "  wheels: 4,", "  engines: 1,", "  seats: 1", "}", "Tenga en cuenta que es importante utilizar la palabra reservaa new cuando se llama a una constructora. Así es como Javascript sabe crear un objeto nuevo y hace que todas las referencias a this dentro del constructor se refieran al objeto nuevo ", "Ahora, una vez que la instancia miCarro se crea, puede ser utilizada como cualquier otro objeto y puedes acceder o modificar sus propiedades como lo harías normalmente. Por ejemplo:", "miCarro.tipoTurbo = \"doble\"; ", "Nuestra variable miCarro tiene ahora una propiedad tipoTurbo con un valor de \"doble\".", "En el editor, utiliza la constructora Car para crear una nueva instancia y asignala a myCar.", "A continuación, dale a myCar una propiedad nickname con un valor tipo cadena." ] }, { "id": "563cfb55594311ffcb333c70", "title": "Make Unique Objects by Passing Parameters to our Constructor", "description": [ "The constructor we have is great, but what if we don't always want to create the same object?", "To solve this we can add parameters to our constructor. We do this like the following example:", "
var Car = function(wheels, seats, engines) {
  this.wheels = wheels;
  this.seats = seats;
  this.engines = engines;
};
", "Now we can pass in arguments when we call our constructor.", "var myCar = new Car(6, 3, 1);", "This code will create an object that uses the arguments we passed in and looks like:", "
{
  wheels: 6,
  seats: 3,
  engines: 1
}
", "Now give it a try yourself! Alter the Car constructor to use parameters to assign values to the wheels, seats, and engines properties.", "Then call your new constructor with three number arguments and assign it to myCar to see it in action." ], "challengeSeed": [ "var Car = function() {", " //Change this constructor", " this.wheels = 4;", " this.seats = 1;", " this.engines = 1;", "};", "", "//Try it out here", "var myCar;" ], "tail": [ "(function() {return JSON.stringify(myCar);})();" ], "solutions": [ "var Car = function(wheels,seats,engines) {\n this.wheels = wheels;\n this.seats = seats;\n this.engines = engines;\n};\n\nvar myCar = new Car(4,1,1);" ], "tests": [ "assert((function(){var testCar = new Car(3,1,2); return testCar.wheels === 3 && testCar.seats === 1 && testCar.engines === 2;})(), 'message: Calling new Car(3,1,2) should produce an object with a wheels property of 3, a seats property of 1, and an engines property of 2.');", "assert((function(){var testCar = new Car(4,4,2); return testCar.wheels === 4 && testCar.seats === 4 && testCar.engines === 2;})(), 'message: Calling new Car(4,4,2) should produce an object with a wheels property of 4, a seats property of 4, and an engines property of 2.');", "assert((function(){var testCar = new Car(2,6,3); return testCar.wheels === 2 && testCar.seats === 6 && testCar.engines === 3;})(), 'message: Calling new Car(2,6,3) should produce an object with a wheels property of 2, a seats property of 6, and an engines property of 3.');", "assert(typeof myCar.wheels === 'number' && typeof myCar.seats === 'number' && typeof myCar.engines === 'number', 'message: myCar should have number values for the wheels, seats, and engines properties.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Crea objetos únicos pasando parámetros a la constructora", "descriptionEs": [ "La constructora que tenemos es fabulosa, pero ¿qué hacer si no queremos crear siempre el mismo objeto?", "Para solucionar esto podemos añadirparámetrosen nuestra constructora. Hacemos esto como en el siguiente ejemplo: ", "var Carro = function (ruedas, asientos, motores) {", "  this.ruedas = ruedas;", "  this.asientos = asientos;", "  this.motores = motores;", "};", "Ahora podemos pasar argumentos cuando llamamos a nuestra constructora.", "var miCarro = nuevo Carro(6, 3, 1); ", "Este código crea un objeto que utiliza los argumentos que pasamos en y se ve así:", "{", "  ruedas: 6,", "  asientos: 3,", "  motores: 1", "}", "¡Ahora date una oportunidad a ti mismo! Modifica la constructora Car para que use parámetros que permitan asignar valores para las propiedades wheels, seats, y engines. ", "Entonces llama a tu nueva constructora con tres argumentos numéricos y asígnala a myCarpara verla en acción." ] }, { "id": "cf1111c1c15feddfaeb3bdef", "title": "Make Object Properties Private", "description": [ "Objects have their own attributes, called properties, and their own functions, called methods.", "In the previous challenges, we used the this keyword to reference public properties of the current object.", "We can also create private properties and private methods, which aren't accessible from outside the object.", "To do this, we create the variable inside the constructor using the var keyword we're familiar with, instead of creating it as a property of this.", "This is useful for when we need to store information about an object but we want to control how it is used by outside code.", "For example, what if we want to store the speed our car is traveling at but we only want outside code to be able to modify it by accelerating or decelerating, so the speed changes in a controlled way?", "In the editor you can see an example of a Car constructor that implements this pattern.", "Now try it yourself! Modify the Bike constructor to have a private property called gear and two public methods called getGear and setGear to get and set that value." ], "challengeSeed": [ "var Car = function() {", " // this is a private variable", " var speed = 10;", "", " // these are public methods", " this.accelerate = function(change) {", " speed += change;", " };", "", " this.decelerate = function() {", " speed -= 5;", " };", "", " this.getSpeed = function() {", " return speed;", " };", "};", "", "var Bike = function() {", "", " // Only change code below this line.", "", "};", "", "var myCar = new Car();", "", "var myBike = new Bike();" ], "tail": [ "if(myBike.hasOwnProperty('getGear')){(function() {return JSON.stringify(myBike.getGear());})();}" ], "solutions": [ "var Car = function() {\n var speed = 10;\n\n this.accelerate = function(change) {\n speed += change;\n };\n\n this.decelerate = function() {\n speed -= 5;\n };\n\n this.getSpeed = function() {\n return speed;\n };\n};\n\nvar Bike = function() {\n var gear = 1;\n \n this.getGear = function() {\n return gear;\n };\n \n this.setGear = function(newGear) {\n gear = newGear;\n };\n};\n\nvar myCar = new Car();\n\nvar myBike = new Bike();" ], "tests": [ "assert(typeof myBike.getGear !== 'undefined' && typeof myBike.getGear === 'function', 'message: The method getGear of myBike should be accessible outside the object.');", "assert(typeof myBike.setGear !== 'undefined' && typeof myBike.setGear === 'function', 'message: The method setGear of myBike should be accessible outside the object.');", "assert(typeof myBike.gear === 'undefined', 'message: myBike.gear should remain undefined.');", "assert.strictEqual((function () { myBike.setGear(4); return myBike.getGear(); })(), 4, 'message: myBike.getGear() should return 4 after calling myBike.setGear(4).');", "assert.strictEqual((function () { myBike.setGear(3); return myBike.getGear(); })(), 3, 'message: myBike.getGear() should return 3 after calling myBike.setGear(3).');", "assert.strictEqual((function () { myBike.setGear(1); return myBike.getGear(); })(), 1, 'message: myBike.getGear() should return 1 after calling myBike.setGear(1).');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Crea propiedades privadas de un objeto", "descriptionEs": [ "Los objetos tienen sus propios atributos, llamados propiedades, y sus propias funciones, llamadasmétodos.", "En los desafíos anteriores, se utilizó la palabra reservada this para referenciar propiedades públicasdel objeto actual.", "También podemos crear propiedades privadas y métodos privados, que no son accesibles desde fuera del objeto.", "Para ello, creamos la variable dentro de la constructora usando la palabra reservada var, con la cual ya estamos familiarizados, en lugar de crearla con this. ", "Esto es útil cuando necesitamos almacenar información sobre un objeto, pero controlando como se usa en el código externo al objeto.", "Por ejemplo, ¿qué pasa si queremos almacenar la velocidad con la cual se desplaza nuestro carro, pero queremos que el código externo pueda modificarla sólo acelerando o desacelerando, de forma que la velocidad cambie de una manera controlada?", "En el editor se puede ver un ejemplo de una constructora de Car que implementa este patrón.", "¡Ahora pruébalo tú mismo! Modifica la constructora Bike para tener una propiedad privada llamada geary dosmétodos públicos llamados getGearysetGear para obtener y establecer ese valor." ] }, { "id": "cf1111c1c15feddfaeb7bdef", "title": "Iterate over Arrays with .map", "description": [ "The map method is a convenient way to iterate through arrays. Here's an example usage:", "
var timesFour = oldArray.map(function(val){
  return val * 4;
});
", "", "The map method will iterate through every element of the array, creating a new array with values that have been modified by the callback function, and return it.", "In our example the callback only uses the value of the array element (the val argument) but your callback can also include arguments for the index and array being acted on.", "Use the map function to add 3 to every value in the variable oldArray." ], "challengeSeed": [ "var oldArray = [1,2,3,4,5];", "var newArray = [];", "", "// Only change code below this line.", "", "newArray = oldArray;" ], "tail": [ "(function() {return newArray;})();" ], "tests": [ "assert.deepEqual(newArray, [4,5,6,7,8], 'message: You should add three to each value in the array.');", "assert(editor.getValue().match(/\\.map\\s*\\(/gi), 'message: You should be making use of the map method.');", "assert(editor.getValue().match(/\\[1\\,2\\,3\\,4\\,5\\]/gi), 'message: You should only modify the array with map.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Iterar sobre vectores con .map", "descriptionEs": [ "El método map es una manera conveniente de iterar sobre vectores. He aquí un ejemplo de uso: ", "var porCuatro = vectorAntiguo.map(function(val){", "  return val * 4;", "});", "", "El método map iterará sobre cada elemento del vector, creando un nuevo vector con los valores modificados por la función de devolución de llamada (callback) y retornará ese nuevo arreglo.", "En nuestro ejemplo, la función de devolución de llamada sólo usa el valor del elemento del vector sobre el que está iterando (parámetro val), pero tu función de devolución de llamada también puede incluir parámetros para el índice y el vector completo. ", "Usa la función map para añadir 3 a cada valor de la variable oldArray." ] }, { "id": "cf1111c1c15feddfaeb8bdef", "title": "Condense arrays with .reduce", "description": [ "The array method reduce is used to iterate through an array and condense it into one value.", "To use reduce you pass in a callback whose arguments are an accumulator (in this case, previousVal) and the current value (currentVal).", "reduce has an optional second argument which can be used to set the initial value of the accumulator. If no initial value is specified it will be the first array element and currentVal will start with the second array element.", "Here is an example of reduce being used to subtract all the values of an array:", "
var singleVal = array.reduce(function(previousVal, currentVal) {
  return previousVal - currentVal;
}, 0);
", "Use the reduce method to sum all the values in array and assign it to singleVal." ], "challengeSeed": [ "var array = [4,5,6,7,8];", "var singleVal = 0;", "", "// Only change code below this line.", "", "singleVal = array;" ], "tail": [ "(function() {return singleVal;})();" ], "tests": [ "assert(singleVal == 30, 'message: singleVal should be equal to the sum of all items in the array variable.');", "assert(editor.getValue().match(/\\.reduce\\s*\\(/gi), 'message: You should have made use of the reduce method.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Condensa vectores con .reduce", "descriptionEs": [ "El método reduce de un vector, se utiliza para iterar a través del vector y condensarlo en un valor.", "Para usar reduce tu le pasas una función de devolución de llamada cuyos argumentos sean un acumulador (en este caso, valorPrevio) y el valor actual (valorActual). ", "reduce tiene un argumento opcional que puede usarse para asignar un valor inicial al acumulador. Si no se especifica ningún valor inicial será el primer elemento del vector y valorActual comenzará en el segundo elemento del vector. ", "He aquí un ejemplo dereduce cuando se utiliza para restar todos los valores de una matriz:", "var singleVal = array.reduce(function(valorAnterior, valorActual) {", "  return valorAnterior - valorActual;", "}, 0);", "Usa el método reduce para sumar todos los valores en array y asignarlo a singleVal." ] }, { "id": "cf1111c1c15feddfaeb9bdef", "title": "Filter Arrays with .filter", "description": [ "The filter method is used to iterate through an array and filter out elements where a given condition is not true.", "filter is passed a callback function which takes the current value (we've called that val) as an argument.", "Any array element for which the callback returns true will be kept and elements that return false will be filtered out.", "The following code is an example of using filter to remove array elements that are equal to five:", "Note: We omit the second and third arguments since we only need the value", "
array = array.filter(function(val) {
  return val !== 5;
});
", "Use filter to remove all elements from oldArray that are greater than 5." ], "challengeSeed": [ "var oldArray = [1,2,3,4,5,6,7,8,9,10];", "var newArray = [];", "", "// Only change code below this line.", "", "newArray = oldArray;" ], "tail": [ "(function() {return newArray;})();" ], "tests": [ "assert.deepEqual(newArray, [1,2,3,4,5], 'message: You should have removed all the values from the array that are greater than 5.');", "assert(editor.getValue().match(/array\\.filter\\s*\\(/gi), 'message: You should be using the filter method to remove the values from the array.');", "assert(editor.getValue().match(/\\[1\\,2\\,3\\,4\\,5\\,6\\,7\\,8\\,9\\,10\\]/gi), 'message: You should only be using filter to modify the contents of the array.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Filtrar vectores con .filter", "descriptionEs": [ "El método filter se utiliza para iterar a través de un vector y filtrar los elementos que hagan falsa un condición determinada.", "filter recibe una función de devolución de llamada que a su vez recibe como argumento el valor actual (que hemos llamado queval ).", "Cualquier elemento del vector para el cual la función de devolución de llamada retorne true se mantendrá y los elementos que devuelven false serán filtrados.", "El código siguiente es un ejemplo del uso del filter para eliminar los elementos de un vector que no sean números pares:", "Nota: Omitimos el segundo y tercer argumentos ya que sólo necesitamos el valor", "array = array.filter(function(val) {", "  return val % 2 === 0;", "});", "Usa filter para eliminar todos los elementos de arrayque sean mayores que 5." ] }, { "id": "cf1111c1c16feddfaeb1bdef", "title": "Sort Arrays with .sort", "description": [ "You can use the method sort to easily sort the values in an array alphabetically or numerically.", "Unlike the previous array methods we have been looking at, sort actually alters the array in place. However, it also returns this sorted array.", "sort can be passed a compare function as a callback. If no compare function is passed in it will convert the values to strings and sort alphabetically.", "Here is an example of using sort with a compare function that will sort the elements from smallest to largest number:", "
var array = [1, 12, 21, 2];
array.sort(function(a, b) {
  return a - b;
});
", "Use sort to sort array from largest to smallest." ], "challengeSeed": [ "var array = [1, 12, 21, 2];", "", "// Only change code below this line.", "", "array.sort();" ], "tail": [ "(function() {return array;})();" ], "tests": [ "assert.deepEqual(array, [21, 12, 2, 1], 'message: You should have sorted the array from largest to smallest.');", "assert(editor.getValue().match(/\\[1,\\s*12,\\s*21,\\s*2\\];/gi), 'message: You should only be using sort to modify the array.');", "assert(editor.getValue().match(/\\.sort\\s*\\(/g), 'message: You should have made use of the sort method.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Ordena vectores con .sort", "descriptionEs": [ "Puedes utilizar el método sort para ordenar alfabética o numéricamente los valores de un vector.", "A diferencia de los métodos de vector que hemos visto,sorten realidad altera el vector en su lugar. Sin embargo, también devuelve este vector ordenado. ", "sort puede recibir como parámetro una función de devolución de llamada para comparar. Sin no se provee una función de comparación, convertirá los valores a cadenas y los ordenará alfabéticamente. ", "He aquí un ejemplo del uso de sort con una función de comparación que ordena los elementos de menor a mayor:", "var array = [1, 12, 21, 2];", "array.sort(function(a, b) {", "  return a - b;", "});", "Usa sort para ordenararray de mayor a menor." ] }, { "id": "cf1111c1c16feddfaeb2bdef", "title": "Reverse Arrays with .reverse", "description": [ "You can use the reverse method to reverse the elements of an array.", "reverse is another array method that alters the array in place, but it also returns the reversed array.", "
var myArray = [1, 2, 3];
myArray.reverse();
", "returns [3, 2, 1]", "Use reverse to reverse the array variable and assign it to newArray." ], "challengeSeed": [ "var array = [1,2,3,4,5,6,7];", "var newArray = [];", "", "// Only change code below this line.", "", "newArray = array;" ], "tail": [ "(function() {return newArray;})();" ], "tests": [ "assert.deepEqual(newArray, [7,6,5,4,3,2,1], 'message: You should reverse the array.');", "assert(editor.getValue().match(/\\.reverse\\s*\\(\\)/gi), 'message: You should use the reverse method.');", "assert(editor.getValue().match(/\\[1\\,2\\,3\\,4\\,5\\,6\\,7/gi), 'message: You should only be using reverse to modify array.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Invierte vectores con .reverse", "descriptionEs": [ "Puedes utilizar el método reverse para invertir los elementos en un vector.", "reverse es otro método de vector que altera el vector mismo, y también devuelve el vector invertido.", "Usa reverse para invertir la variable array y asignarla a newArray." ] }, { "id": "cf1111c1c16feddfaeb3bdef", "title": "Concatenate Arrays with .concat", "description": [ "concat can be used to merge the contents of two arrays into one.", "concat takes an array as an argument and returns a new array with the elements of this array concatenated onto the end.", "Here is an example of concat being used to concatenate otherArray onto the end of oldArray:", "newArray = oldArray.concat(otherArray);", "Use .concat() to concatenate concatMe onto the end of oldArray and assign it to newArray." ], "challengeSeed": [ "var oldArray = [1,2,3];", "var newArray = [];", "", "var concatMe = [4,5,6];", "", "// Only change code below this line.", "", "newArray = oldArray;" ], "tail": [ "(function() {return newArray;})();" ], "tests": [ "assert.deepEqual(newArray, [1,2,3,4,5,6], 'message: You should concatenate the two arrays together.');", "assert(editor.getValue().match(/\\.concat\\s*\\(/gi), 'message: You should be using the concat method to merge the two arrays.');", "assert(editor.getValue().match(/\\[1\\,2\\,3\\]/gi) && editor.getValue().match(/\\[4\\,5\\,6\\]/gi), 'message: You should only be using concat to modify the arrays.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Concatena vectores con .concat", "descriptionEs": [ "concat se puede utilizar para combinar el contenido de dos vectores en uno solo.", "concat recibe un vector como argumento y devuelve un nuevo vector con los elementos del vector que recibe concatenados al final.", "He aquí un ejemplo de concat cuando se usa para concatenar otroVector al final de vectorAntiguo:", "vectorNuevo = vectorAntiguo.concat(otroVector);", "Usa .concat () para concatenar concatMe al final de oldArrayy asigna el vector resultante a newArray." ] }, { "id": "cf1111c1c16feddfaeb4bdef", "title": "Split Strings with .split", "description": [ "You can use the split method to split a string into an array.", "split uses the argument you pass in as a delimiter to determine which points the string should be split at.", "Here is an example of split being used to split an array at every s character:", "var array = string.split('s');", "Use split to create an array of words from string and assign it to array." ], "challengeSeed": [ "var string = \"Split me into an array\";", "var array = [];", "", "// Only change code below this line.", "", "array = string;" ], "tail": [ "(function() {return array;})();" ], "tests": [ "assert(/\\.split\\(/gi, 'message: You should use the split method on the string.');", "assert(typeof array === 'object' && array.length === 5, 'message: You should split the string by its spaces.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Divide cadenas con .split", "descriptionEs": [ "Puedes utilizar el método split para dividir una cadena en un vector.", "split utiliza el argumento que recibe como delimitador para determinar en qué puntos debe dividir la cadena.", "He aquí un ejemplo del uso de split para dividir una cadena en cada caracter s:", "var vector = string.split('s');", "Usa split para crear un vector con las palabras de una cadena y asígnalo a la variable array." ] }, { "id": "cf1111c1c16feddfaeb5bdef", "title": "Join Strings with .join", "description": [ "We can use the join method to join each element of an array into a string separated by whatever delimiter you provide as an argument.", "The following is an example of using join to join all of the elements of an array into a string with all the elements separated by word `Na`:", "
var joinMe = [\"Na \", \"Na \", \"Na \", \"Na \", \"Batman!\"];
var joinedString = joinMe.join(\"Na \");
console.log(joinedString);
", "Use the join method to create a string from joinMe with spaces in between each element and assign it to joinedString." ], "challengeSeed": [ "var joinMe = [\"Split\",\"me\",\"into\",\"an\",\"array\"];", "var joinedString = '';", "", "// Only change code below this line.", "", "joinedString = joinMe;" ], "tail": [ "(function() {return joinedString;})();" ], "tests": [ "assert(typeof joinedString === 'string' && joinedString === \"Split me into an array\", 'message: You should join the elements of the array with spaces.');", "assert(/\\.join\\(/gi, 'message: You should use of the join method on the array.');" ], "type": "waypoint", "challengeType": 1, "nameEs": "Une cadenas con .join", "descriptionEs": [ "Podemos usar el método join para unir los elementos de un vector en una cadena, separandolos con el delimitador que proporciones como argumento.", "El siguiente es un ejemplo del uso de join para unir todos los elementos de un vector en una cadena con todos los elementos separados entre si por palabra` Na`: ", "var uneme = [\"Na \", \"Na \", \"Na \", \"Na \", \"Batman!\"];", "var cadenaUnida = uneme.join(\"Na \");", "console.log(cadenaUnida);", "Usa el método join para crear una cadena a partir joinMe con espacios entre cada par de elementos y asignarla a joinedString ." ] } ] }