2344 lines
119 KiB
JSON
Raw Normal View History

2015-07-05 17:12:52 -07:00
{
"name": "Basic JavaScript",
"order": 6,
"time": "10h",
2015-07-05 17:12:52 -07:00
"challenges": [
{
"id": "bd7123c9c441eddfaeb4bdef",
2015-08-07 23:37:32 -07:00
"title": "Comment your JavaScript Code",
"description": [
"Comments are lines of code that your computer will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.",
2015-08-14 14:40:02 -07:00
"Let's take a look at the two ways you can write comments in JavaScript.",
"The double-slash comment will comment out the remainder of the text on the current line:",
"<code>// This is a comment.</code>",
"The slash-star-star-slash comment will comment out everything between the <code>/*</code> and the <code>*/</code> characters:",
"<code>/* This is also a comment */</code>",
"Try creating one of each."
],
"tests": [
"assert(editor.getValue().match(/(\\/\\/)...../g), 'message: Create a <code>//</code> style comment that contains at least five letters.');",
"assert(editor.getValue().match(/(\\/\\*)[\\w\\W]{5,}(?=\\*\\/)/gm), 'message: Create a <code>/* */</code> style comment that contains at least five letters.');",
"assert(editor.getValue().match(/(\\*\\/)/g), 'message: Make sure that you close the comment with a <code>*/</code>.');"
],
"challengeSeed": [],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Agrega comentarios a tu código JavaScript",
"descriptionEs": [
"Los comentarios son líneas de código que el computador ignorará intencionalmente. Los comentarios son una gran forma de dejarte notas a ti mismo y a otras personas que luego tendrán que averiguar lo que hace que el código. ",
"Vamos a echar un vistazo a las dos maneras en las que puedes agregar tus comentarios en JavaScript.",
"El comentario de doble barra comentará el resto del texto en la línea donde se ubica:",
"<code>// Este es un comentario.</code>",
"El comentario de barra-estrella-estrella-barra, comentará todo lo que haya entre los caracteres <code>/*</code> y <code>*/</code>:",
"<code>/* Este es también un comentario */</code>",
"Trata de crear uno de cada uno."
]
},
2015-07-05 17:12:52 -07:00
{
"id": "bd7123c9c441eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Understand Boolean Values",
2015-07-05 17:12:52 -07:00
"description": [
"In computer science, <code>data structures</code> are things that hold data. JavaScript has seven of these. For example, the <code>Number</code> data structure holds numbers.",
"Let's learn about the most basic data structure of all: the <code>Boolean</code>. Booleans can only hold the value of either true or false. They are basically little on-off switches.",
"Let's modify our <code>welcomeToBooleans</code> function so that it will return <code>true</code> instead of <code>false</code> when the run button is clicked."
2015-07-05 17:12:52 -07:00
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert(typeof welcomeToBooleans() === 'boolean', 'message: The <code>welcomeToBooleans()</code> function should return a boolean &#40;true/false&#41; value.');",
"assert(welcomeToBooleans() === true, 'message: <code>welcomeToBooleans()</code> should return true.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
"function welcomeToBooleans() {",
"",
"// Only change code below this line.",
"",
" return false;",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"}"
],
"tail": [
2015-07-05 17:12:52 -07:00
"welcomeToBooleans();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Entiende los valores booleanos",
"descriptionEs": [
"En informática las <code>estructuras de datos</code> son cosas que contienen datos. JavaScript tiene siete de estas. Por ejemplo, la estructura de datos <code>Número</code> contiene números. ",
"Vamos a aprender acerca de la estructura de datos más básica de todas: el <code>Boolean</code>. Los booleanos sólo puede contener el valor verdadero o el valor falso. Son básicamente pequeños interruptores de encendido y apagado. ",
"Vamos a modificar nuestra función <code>welcomeToBooleans</code> para que devuelva <code>true</code> en lugar de <code>false</code> cuando se pulse el botón de ejecución."
]
2015-07-05 17:12:52 -07:00
},
{
"id": "bd7123c9c443eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Declare JavaScript Variables",
2015-07-05 17:12:52 -07:00
"description": [
"When we store data in a <code>data structure</code>, we call it a <code>variable</code>. These variables are no different from the x and y variables you use in math.",
"Let's create our first variable and call it \"myName\".",
"You'll notice that in <code>myName</code>, we didn't use a space, and that the \"N\" is capitalized. JavaScript variables are written in <code>camel case</code>. An example of camel case is: camelCase.",
"Now, use the <code>var</code> keyword to create a variable called <code>myName</code>. Set its value to your name, in double quotes.",
2015-07-05 17:12:52 -07:00
"Look at the <code>ourName</code> example if you get stuck."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof myName !== \"undefined\" && typeof myName === \"string\" && myName.length > 0){return true;}else{return false;}})(), 'message: <code>myName</code> should be a string that contains at least one character in it.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
2015-10-28 05:13:49 -07:00
"var ourName = \"Free Code Camp\";",
"",
""
],
"tail": [
2015-11-20 23:39:25 -08:00
"if(typeof myName !== \"undefined\"){(function(v){return v;})(myName);}"
2015-07-05 17:12:52 -07:00
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Declara variables en JavaScript",
"descriptionEs": [
"Cuando almacenamos datos en una <code>estructura de datos</code>, la llamamos una <code>variable</code>. Estas variables no son diferentes de las variables x e y que utilizas en matemáticas. ",
"Vamos a crear nuestra primera variable y a llamarla \"myName\".",
"Te darás cuenta que en <code>myName</code>, no usamos un espacio, y que la \" N\"se escribe con mayúscula. Las variables en JavaScript se escriben con <code>capitalización camello (camel case)</code>. Un ejemplo de capitalización camello: capitalizacionCamello.",
"Ahora, utiliza la palabra clave <code>var</code> para crear una variable llamada <code>myName</code>. Establecele como valor tu nombre, entre comillas dobles. ",
"Mira el ejemplo con <code>ourName</code> si te quedas atascado."
]
2015-07-05 17:12:52 -07:00
},
{
"id": "bd7123c9c444eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Declare String Variables",
2015-07-05 17:12:52 -07:00
"description": [
"In the previous challenge, we used the code <code>var myName = \"your name\"</code>. This is what we call a <code>String</code> variable. It is nothing more than a \"string\" of characters. JavaScript strings are always wrapped in quotes.",
"Now let's create two new string variables: <code>myFirstName</code> and <code>myLastName</code> and assign them the values of your first and last name, respectively."
2015-07-05 17:12:52 -07:00
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof myFirstName !== \"undefined\" && typeof myFirstName === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'message: <code>myFirstName</code> should be a string with at least one character in it.');",
"assert((function(){if(typeof myLastName !== \"undefined\" && typeof myLastName === \"string\" && myLastName.length > 0){return true;}else{return false;}})(), 'message: <code>myLastName</code> should be a string with at least one character in it.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
2015-10-28 05:13:49 -07:00
"var firstName = \"Alan\";",
"var lastName = \"Turing\";",
2015-07-05 17:12:52 -07:00
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof myFirstName !== \"undefined\" && typeof myLastName !== \"undefined\"){(function(){return myFirstName + ', ' + myLastName;})();}"
2015-07-05 17:12:52 -07:00
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Declara variables tipo cadena",
"descriptionEs": [
"En el reto anterior, se utilizó el código <code>myName var = \"su nombre\"</code>. Esto es lo que llamamos una variable tipo <code>cadena</code>. No es nada más que una \"cadena\" de caracteres. Las cadenas en JavaScript siempre se encierran entre comillas. ",
"Ahora vamos a crear dos nuevas variables tipo cadena: <code>myFirstName</code> y <code>myLastName</code> y asignarles los valores de tu nombre y tu apellido, respectivamente."
]
2015-07-05 17:12:52 -07:00
},
{
"id": "bd7123c9c448eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Check the Length Property of a String Variable",
2015-07-05 17:12:52 -07:00
"description": [
"<code>Data structures</code> have <code>properties</code>. For example, <code>strings</code> have a property called <code>.length</code> that will tell you how many characters are in the string.",
"For example, if we created a variable <code>var firstName = \"Charles\"</code>, we could find out how long the string \"Charles\" is by using the <code>firstName.length</code> property.",
2015-08-18 09:34:34 -04:00
"Use the <code>.length</code> property to count the number of characters in the <code>lastName</code> variable."
2015-07-05 17:12:52 -07:00
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof lastNameLength !== \"undefined\" && typeof lastNameLength === \"number\" && lastNameLength === 8){return true;}else{return false;}})(), 'message: <code>lastNameLength</code> should be equal to eight.');",
"assert((function(){if(editor.getValue().match(/\\.length/gi) && editor.getValue().match(/\\.length/gi).length >= 2 && editor.getValue().match(/var lastNameLength \\= 0;/gi) && editor.getValue().match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'message: You should be getting the length of <code>lastName</code> by using <code>.length</code> like this: <code>lastName.length</code>.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
"var firstNameLength = 0;",
"var lastNameLength = 0;",
"var firstName = \"Ada\";",
2015-07-05 17:12:52 -07:00
"",
"firstNameLength = firstName.length;",
2015-07-05 17:12:52 -07:00
"",
"var lastName = \"Lovelace\";",
2015-07-05 17:12:52 -07:00
"",
"// Only change code below this line.",
2015-08-15 13:57:44 -07:00
"",
"lastNameLength = lastName;",
2015-07-05 17:12:52 -07:00
"",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof lastNameLength !== \"undefined\"){(function(){return lastNameLength;})();}"
2015-07-05 17:12:52 -07:00
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Comprueba la propiedad longitud (length) de una variable tipo cadena",
"descriptionEs": [
"Las <code>estructuras de datos</code> tienen <code>propiedades</code>. Por ejemplo, las <code>cadenas</code> tienen una propiedad llamada <code>.length </code> que te dirá cuántos caracteres hay en la cadena.",
"Por ejemplo, si creamos una variable <code>var firstName=\"Charles\"</code>, podemos averiguar la longitud de la cadena \"Charles\" usando la propiedad <code>firstName.length</code>. ",
"Usa la propiedad <code>.length</code> para contar el número de caracteres en el variable <code>lastName</code>."
]
2015-07-05 17:12:52 -07:00
},
{
"id": "bd7123c9c549eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Use Bracket Notation to Find the First Character in a String",
2015-07-05 17:12:52 -07:00
"description": [
"<code>Bracket notation</code> is a way to get a character at a specific <code>index</code> within a string.",
"Computers don't start counting at 1 like humans do. They start at 0.",
"For example, the character at index 0 in the word \"Charles\" is \"C\". So if <code>var firstName = \"Charles\"</code>, you can get the value of the first letter of the string by using <code>firstName[0]</code>.",
"Use <code>bracket notation</code> to find the first character in the <code>lastName</code> variable and assign it to <code>firstLetterOfLastName</code>.",
2015-07-05 17:12:52 -07:00
"Try looking at the <code>firstLetterOfFirstName</code> variable declaration if you get stuck."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof firstLetterOfLastName !== \"undefined\" && editor.getValue().match(/\\[0\\]/gi) && typeof firstLetterOfLastName === \"string\" && firstLetterOfLastName === \"L\"){return true;}else{return false;}})(), 'message: The <code>firstLetterOfLastName</code> variable should have the value of <code>L</code>.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
2015-08-17 09:52:34 -04:00
"var firstLetterOfFirstName = \"\";",
"var firstLetterOfLastName = \"\";",
"",
"var firstName = \"Ada\";",
2015-07-05 17:12:52 -07:00
"",
"firstLetterOfFirstName = firstName[0];",
2015-07-05 17:12:52 -07:00
"",
"var lastName = \"Lovelace\";",
2015-07-05 17:12:52 -07:00
"",
"firstLetterOfLastName = lastName;",
2015-07-05 17:12:52 -07:00
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(v){return v;})(firstLetterOfLastName);"
2015-07-05 17:12:52 -07:00
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa la notación de corchetes para encontrar el primer acaracter de una cadena",
"descriptionEs": [
"La <code>notación de corchetes</code> es una forma de obtener el caracter en un <code>índice</code> específico de una cadena.",
"Los computadoras no empiezan a contar desde 1 como hacen los humanos. Comienzan en 0 ",
"Por ejemplo, el caracter en el índice 0 en la palabra \"Charles \" es \"C\". Entonces si <code>var firstName = \"Charles\"</code>, puedes obtener la primera letra de la cadena usando <code>firstName[0]</code> .",
"Usa la <code>notación de corchetes</code> para encontrar el primer caracter en la variable <code>lastName</code> y asignarlo a <code>firstLetterOfLastName</code>.",
"Si te atascas intenta mirar la declaración de la variable <code>firstLetterOfFirstName</code>."
]
2015-07-05 17:12:52 -07:00
},
{
"id": "bd7123c9c450eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Use Bracket Notation to Find the Nth Character in a String",
2015-07-05 17:12:52 -07:00
"description": [
"You can also use <code>bracket notation</code> to get the character at other positions within a string.",
"Remember that computers start counting at 0, so the first character is actually the zeroth character.",
"Let's try to set <code>thirdLetterOfLastName</code> to equal the <code>third letter</code> of the <code>lastName</code> variable.",
2015-07-05 17:12:52 -07:00
"Try looking at the <code>secondLetterOfFirstName</code> variable declaration if you get stuck."
],
"tests": [
"assert(thirdLetterOfLastName === 'v', 'message: The <code>thirdLetterOfLastName</code> variable should have the value of <code>v</code>.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
"var firstName = \"Ada\";",
2015-07-05 17:12:52 -07:00
"",
"var secondLetterOfFirstName = firstName[1];",
"",
"var lastName = \"Lovelace\";",
2015-07-05 17:12:52 -07:00
"",
"var thirdLetterOfLastName = lastName;",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(v){return v;})(thirdLetterOfLastName);"
2015-07-05 17:12:52 -07:00
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa la notación de corchetes para encontrar el n-ésimo caracter en una cadena",
"descriptionEs": [
"También puede usar <code>notación de corchetes</code> para obtener el caracter en otras posiciones dentro de una cadena.",
"Recuerda que los computadores empiezan a contar a 0, por lo que el primer caracter es en realidad el caracter cero.",
"Vamos a tratar de asignar a <code>thirdLetterOfLastName</code> la <code>tercera letra</code> de la variable <code>lastName</code>.",
"Si te atascas intenta mirar la declaración de la variable <code>secondLetterOfFirstName</code>."
]
2015-07-05 17:12:52 -07:00
},
{
"id": "bd7123c9c451eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Use Bracket Notation to Find the Last Character in a String",
2015-07-05 17:12:52 -07:00
"description": [
"In order to get the last letter of a string, you can subtract one from the string's length.",
"For example, if <code>var firstName = \"Charles\"</code>, you can get the value of the last letter of the string by using <code>firstName[firstName.length - 1]</code>.",
"Use <code>bracket notation</code> to find the last character in the <code>lastName</code> variable.",
"Try looking at the <code>lastLetterOfFirstName</code> variable declaration if you get stuck."
2015-07-05 17:12:52 -07:00
],
"tests": [
"assert(lastLetterOfLastName === \"e\", 'message: <code>lastLetterOfLastName</code> should be \"e\".');",
"assert(editor.getValue().match(/\\.length/g).length === 2, 'message: You have to use <code>.length</code> to get the last letter.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
"var firstName = \"Ada\";",
2015-07-05 17:12:52 -07:00
"",
"var lastLetterOfFirstName = firstName[firstName.length - 1];",
"",
"var lastName = \"Lovelace\";",
2015-07-05 17:12:52 -07:00
"",
"var lastLetterOfLastName = lastName;",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(v){return v;})(lastLetterOfLastName);"
2015-07-05 17:12:52 -07:00
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa notación de corchetes para encontrar el último caracter de una cadena",
"descriptionEs": [
"Con el fin de conseguir la última letra de una cadena, puedes restar uno a la longitud de la cadena.",
"Por ejemplo, si <code>var firstName = \"Charles\"</code>, se puede obtener la última letra usando <code>firstName[firstName.length - 1]</code>. ",
"Utiliza <code>notación de corchetes</code> para encontrar el último caracter de la variabel <code>lastName</code>.",
"Si te atascas intenta mirando la declaración de la variable <code>lastLetterOfFirstName</code>."
]
2015-07-05 17:12:52 -07:00
},
{
"id": "bd7123c9c452eddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Use Bracket Notation to Find the Nth-to-Last Character in a String",
2015-07-05 17:12:52 -07:00
"description": [
"You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.",
2015-10-28 05:13:49 -07:00
"For example, you can get the value of the third-to-last letter of the <code>var firstName = \"Charles\"</code> string by using <code>firstName[firstName.length - 3]</code>",
"Use <code>bracket notation</code> to find the second-to-last character in the <code>lastName</code> string.",
"Try looking at the <code>thirdToLastLetterOfFirstName</code> variable declaration if you get stuck."
2015-07-05 17:12:52 -07:00
],
"tests": [
"assert(secondToLastLetterOfLastName === 'c', 'message: <code>secondToLastLetterOfLastName</code> should be \"c\".');",
"assert(editor.getValue().match(/\\.length/g).length === 2, 'message: You have to use <code>.length</code> to get the second last letter.');"
2015-07-05 17:12:52 -07:00
],
"challengeSeed": [
"var firstName = \"Ada\";",
2015-07-05 17:12:52 -07:00
"",
"var thirdToLastLetterOfFirstName = firstName[firstName.length - 3];",
2015-07-05 17:12:52 -07:00
"",
"var lastName = \"Lovelace\";",
2015-07-05 17:12:52 -07:00
"",
"var secondToLastLetterOfLastName = lastName;",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(v){return v;})(secondToLastLetterOfLastName);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa notación de corchetes para encontrar el n-ésimo último caracter de una cadena",
"descriptionEs": [
"Puede utilizar el mismo principio utilizamos para recuperar el último caracter de una cadena para recuperar el n-ésimo último caracter.",
"Por ejemplo, se puede obtener el valor de la tercera última letra de la cadena <code>var firstName = \"Charles\"</code> utilizando <code>firstName[firstName.length - 3]</code> ",
"Usa <code>notación de corchete</code> para encontrar el segundo último caracter de la cadena en <code>lastName</code>.",
"Si te atascas intenta mirando la declaración de la variable <code>thirdToLastLetterOfFirstName</code>."
]
},
{
"id": "cf1111c1c11feddfaeb3bdef",
2015-08-07 23:37:32 -07:00
"title": "Add Two Numbers with JavaScript",
"description": [
"Let's try to add two numbers using JavaScript.",
"JavaScript uses the <code>+</code> symbol for addition.",
"Change the <code>0</code> so that sum will equal <code>20</code>."
],
"tests": [
"assert((function(){if(sum === 20 && editor.getValue().match(/\\+/g).length >= 2){return true;}else{return false;}})(), 'message: Make the variable <code>sum</code> equal 20.');"
],
"challengeSeed": [
"var sum = 10 + 0;",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(z){return 'sum='+z;})(sum);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Suma dos números con JavaScript",
"descriptionEs": [
"Intentemos sumar dos números con JavaScript.",
"JavaScript utiliza el símbolo <code>+</code> para la adición.",
"Cambie el <code>0</code> para que la suma seá igual a <code>20</code>."
]
},
{
"id": "cf1111c1c11feddfaeb4bdef",
2015-08-07 23:37:32 -07:00
"title": "Subtract One Number from Another with JavaScript",
"description": [
"We can also subtract one number from another.",
2015-09-17 01:04:00 -07:00
"JavaScript uses the <code>-</code> symbol for subtraction.",
"Change the <code>0</code> so that difference will equal <code>12</code>."
],
"tests": [
"assert((function(){if(difference === 12 && editor.getValue().match(/\\-/g)){return true;}else{return false;}})(), 'message: Make the variable <code>difference</code> equal 12.');"
],
"challengeSeed": [
2015-10-28 05:13:49 -07:00
"var difference = 45 - 0;",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(z){return 'difference='+z;})(difference);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Resta un número de otro con JavaScript",
"descriptionEs": [
"También podemos restar un número de otro.",
"JavaScript utiliza el símbolo <code>-</code> de sustracción",
"Cambia el <code>0</code> para que la diferencia sea <code>12</code>."
]
},
{
2015-07-25 20:22:13 -07:00
"id": "cf1231c1c11feddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Multiply Two Numbers with JavaScript",
"description": [
"We can also multiply one number by another.",
2015-09-17 01:04:00 -07:00
"JavaScript uses the <code>*</code> symbol for multiplication.",
"Change the <code>0</code> so that product will equal <code>80</code>."
],
"tests": [
"assert((function(){if(product === 80 && editor.getValue().match(/\\*/g)){return true;}else{return false;}})(), 'message: Make the variable <code>product</code> equal 80.');"
],
"challengeSeed": [
"var product = 8 * 0;",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(z){return 'product='+z;})(product);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Multiplica dos números con JavaScript",
"descriptionEs": [
"También podemos multiplicar un número por otro.",
"JavaScript utiliza el símbolo <code>*</code> de la multiplicación.",
"Cambie el <code>0</code> para que el producto sea igual a <code>80</code>."
]
},
{
"id": "cf1111c1c11feddfaeb6bdef",
2015-08-07 23:37:32 -07:00
"title": "Divide One Number by Another with JavaScript",
"description": [
"We can also divide one number by another.",
2015-09-17 01:04:00 -07:00
"JavaScript uses the <code>/</code> symbol for division.",
"Change the <code>0</code> so that quotient will equal <code>2</code>."
],
"tests": [
"assert((function(){if(quotient === 2 && editor.getValue().match(/var\\s*?quotient\\s*?\\=\\s*?\\d+\\s*?\\/\\s*?\\d+\\s*?;/g)){return true;}else{return false;}})(), 'message: Make the variable <code>quotient</code> equal 2.');"
],
"challengeSeed": [
"var quotient = 66 / 0;",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(z){return 'quotient='+z;})(quotient);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Divide un número por otro con JavaScript",
"descriptionEs": [
"También podemos dividir un número por otro.",
"JavaScript utiliza el símbolo <code>/</code> para dividir.",
"Cambia el <code>0</code> para que el cociente sea igual a <code>2</code>."
]
},
{
2015-07-25 20:22:13 -07:00
"id": "cf1391c1c11feddfaeb4bdef",
2015-08-07 23:37:32 -07:00
"title": "Create Decimal Numbers with JavaScript",
"description": [
"JavaScript number variables can also have decimals.",
"Let's create a variable <code>myDecimal</code> and give it a decimal value."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof myDecimal !== \"undefined\" && typeof myDecimal === \"number\" && editor.getValue().match(/\\./g).length >=2){return true;}else{return false;}})(), 'message: <code>myDecimal</code> should be a decimal point number.');"
],
"challengeSeed": [
"var ourDecimal = 5.7;",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"(function(){if(typeof myDecimal !== \"undefined\"){return myDecimal;}})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Crea números decimales con JavaScript",
"descriptionEs": [
"Las variables tipo número en JavaScript también pueden tener decimales.",
"Vamos a crear una variable <code>myDecimal</code> y a darle un valor decimal."
]
},
{
"id": "bd7993c9c69feddfaeb7bdef",
"title": "Multiply Two Decimals with JavaScript",
"description": [
"In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.",
"Let's multiply two decimals together to get their product.",
"Change the <code>0.0</code> so that product will equal <code>5.0</code>."
],
"tests": [
"assert((function(){if(product === 5.0 && editor.getValue().match(/\\*/g)){return true;}else{return false;}})(), 'message: Make the variable <code>product</code> equal 5.0.');"
],
"challengeSeed": [
"var product = 2.0 * 0.0;",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(y){return 'product='+y;})(product);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Multiplica dos decimales con JavaScript",
"descriptionEs": [
"En JavaScript, también puedes realizar cálculos con números decimales, al igual que con números enteros.",
"Vamos a multiplicar dos números decimales para obtener su producto.",
"Cambia el <code>0.0</code> para que el producto sea igual a <code>5.0</code>."
]
},
{
"id": "bd7993c9ca9feddfaeb7bdef",
"title": "Divide one Decimal by Another with JavaScript",
"description": [
"Now let's divide one decimal by another.",
"Change the <code>0.0</code> so that your quotient will equal <code>2.2</code>."
],
"tests": [
2015-10-28 05:13:49 -07:00
"assert((function(){if(quotient === 2.2 && editor.getValue().match(/\\//g)){return true;}else{return false;}})(), 'message: Make the variable <code>quotient</code> equal <code>2.2</code>.');"
],
"challengeSeed": [
2015-10-28 05:13:49 -07:00
"var quotient = 0.0 / 2.0;",
"",
"",
"// Only change code above this line.",
"",
"(function(y){return 'quotient='+y;})(quotient);"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Divide un número decimal por otro con JavaScript",
"descriptionEs": [
"Ahora vamos a dividir un decimal por otro.",
"Cambia el <code>0.0</code> para que tu cociente sea igual a <code>2.2</code>."
]
},
{
"id": "bd7993c9c69feddfaeb8bdef",
2015-08-07 23:37:32 -07:00
"title": "Store Multiple Values in one Variable using JavaScript Arrays",
"description": [
"With JavaScript <code>array</code> variables, we can store several pieces of data in one place.",
"You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this: <code>var sandwich = [\"peanut butter\", \"jelly\", \"bread\"]</code>.",
"Now let's create a new array called <code>myArray</code> that contains both a <code>string</code> and a <code>number</code> (in that order).",
2015-09-13 23:26:03 -07:00
"Refer to the commented code in the text editor if you get stuck."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert(typeof myArray == 'object', 'message: <code>myArray</code> should be an <code>array</code>.');",
"assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string', 'message: The first item in <code>myArray</code> should be a <code>string</code>.');",
"assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number', 'message: The second item in <code>myArray</code> should be a <code>number</code>.');"
],
"challengeSeed": [
2015-10-28 05:13:49 -07:00
"var array = [\"John\", 23];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
"var myArray = [];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(z){return z;})(myArray);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Almacena múltiples valores en una variable utilizando vectores en JavaScript",
"descriptionEs": [
"Con las variables tipo <code>vector</code> (o en inglés <code>array</code>) podemos almacenar diversos datos en un solo lugar.",
"Empiezas la declaración de un vector con un corchete de apertura, y terminas con un corchete de cierre, y pones una coma entre cada entrada, así: <code>var sandwich = [\"mantequilla de maní\", \"jalea\" , \"pan\"]</code>. ",
"Ahora vamos a crear un nuevo vector llamado <code>myArray</code> que contenga una <code>cadena</code> y un <code>número</code> (en ese orden).",
"Consulta el código comentado en el editor de texto si te atascas."
]
},
{
"id": "cf1111c1c11feddfaeb7bdef",
2015-08-07 23:37:32 -07:00
"title": "Nest one Array within Another Array",
"description": [
2015-09-13 23:26:03 -07:00
"You can also nest arrays within other arrays, like this: <code>[[\"Bulls\", 23]]</code>.",
"Let's now go create a nested array called <code>myArray</code>."
],
"tests": [
"assert(Array.isArray(myArray) && myArray.some(Array.isArray), 'message: <code>myArray</code> should have at least one array nested within another array.');"
],
"challengeSeed": [
"var ourArray = [[\"the universe\", \"everything\", 42]];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
"var myArray = [];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Anida un vector dentro de otro vector",
"descriptionEs": [
"También puedes anidar vectores dentro de otros vectores, como este: <code>[[\"Bulls\", 23]]</code>.",
"Ahora vamos a crear un vector anidado llamado <code>myArray</code>."
]
},
{
"id": "bg9997c9c79feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Access Array Data with Indexes",
"description": [
"We can access the data inside arrays using <code>indexes</code>.",
"Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array.",
"For example:",
"<code>var array = [1,2,3];</code>",
"<code>array[0]; //equals 1</code>",
"<code>var data = array[1];</code>",
"Create a variable called <code>myData</code> and set it to equal the first value of <code>myArray</code>."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof myArray != 'undefined' && typeof myData != 'undefined' && myArray[0] == myData){return true;}else{return false;}})(), 'message: The variable <code>myData</code> should equal the first value of <code>myArray</code>.');"
],
"challengeSeed": [
2015-10-28 05:13:49 -07:00
"var ourArray = [1,2,3];",
"",
"var ourData = ourArray[0]; // equals 1",
"",
"var myArray = [1,2,3];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof myArray !== \"undefined\" && typeof myData !== \"undefined\"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Accede a los datos de un vector mediante índices",
"descriptionEs": [
"Podemos acceder a los datos dentro de los vectores usando <code>índices</code>.",
"Los índices del vector se escriben en la misma notación con corchetes usado con cadenas, excepto que en lugar de especificar un caracter, especifican un elemento del vector.",
"Por ejemplo:",
"<code>var array = [1,2,3];</code>",
"<code>array[0]; //es igual a 1</code>",
"<code>var data = array[1];</code>",
"Crea una variable llamada <code>myData</ code> y asignale el primer valor del vector <code>myArray</code>."
]
},
{
"id": "cf1111c1c11feddfaeb8bdef",
2015-08-07 23:37:32 -07:00
"title": "Modify Array Data With Indexes",
"description": [
"We can also modify the data stored in arrays by using indexes.",
"For example:",
"<code>var ourArray = [3,2,1];</code>",
"<code>ourArray[0] = 1; // equals [1,2,1]</code>",
"Now modify the data stored at index 0 of <code>myArray</code> to the value of 3."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof myArray != 'undefined' && myArray[0] == 3 && myArray[1] == 2 && myArray[2] == 3){return true;}else{return false;}})(), 'message: <code>myArray</code> should now be [3,2,3].');",
"assert((function(){if(editor.getValue().match(/myArray\\[0\\]\\s?=\\s?/g)){return true;}else{return false;}})(), 'message: You should be using correct index to modify the value in <code>myArray</code>.');"
],
"challengeSeed": [
"var ourArray = [1,2,3];",
2015-10-28 05:13:49 -07:00
"",
"ourArray[1] = 3; // ourArray now equals [1,3,3].",
"",
"var myArray = [1,2,3];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
"",
2015-10-28 05:13:49 -07:00
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Modifica datos de un vector usando índices",
"descriptionEs": [
"También podemos modificar los datos almacenados en vectores usando índices.",
"Por ejemplo:",
"<code>var ourArray = [3,2,1];</code>",
"<code>ourArray[0] = 1; // equals [1,2,1]</code>",
"Ahora establece el dato almacenado en el índice 0 de <code>myArray</code> para que sea el valor 3."
]
},
{
"id": "bg9994c9c69feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Manipulate Arrays With pop()",
"description": [
"Another way to change the data in an array is with the <code>.pop()</code> function.",
"<code>.pop()</code> is used to \"pop\" a value off of the end of an array. We can store this \"popped off\" variable by performing <code>pop()</code> within a variable declaration.",
"Any type of data structure can be \"popped\" off of an array - numbers, strings, even nested arrays.",
"Use the <code>.pop()</code> function to remove the last item from <code>myArray</code>, assigning the \"popped off\" value to <code>removedFromMyArray</code>."
],
"tests": [
"assert((function(d){if(d[0] == 'John' && d[1] == 23 && d[2] == undefined){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should only contain <code>[\"John\", 23]</code>.');",
2015-10-28 05:13:49 -07:00
"assert((function(d){if(d[0] == 'cat' && d[1] == 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), 'message: <code>removedFromMyArray</code> should only contain <code>[\"cat\", 2]</code>.');"
],
"challengeSeed": [
"var ourArray = [1,2,3];",
2015-10-28 05:13:49 -07:00
"",
"var removedFromOurArray = ourArray.pop(); // removedFromOurArray now equals 3, and ourArray now equals [1,2]",
"",
"var myArray = [\"John\", 23, [\"cat\", 2]];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
2015-10-28 05:13:49 -07:00
"var removedFromMyArray;",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
"(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con pop()",
"descriptionEs": [
"Otra forma de cambiar los datos en un vector es con la función <code>.pop()</code>.",
"<code>.pop()</code> se utiliza para \"sacar\" el valor final de un vector. Podemos almacenar el valor \"sacado\" asignando <code>pop</code> a una variable por ejemplo durante su declaración.",
"Todo tipo de datos puede ser \"sacado\" de un vector --números, cadenas, incluso los vectores anidadas.",
"Usa la función <code>.pop()</code> para sacar el último elemento de <code>myArray</code> y asigna ese valor \"sacado\" a <code>removedFromMyArray </code>."
]
},
{
"id": "bg9995c9c69feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Manipulate Arrays With push()",
"description": [
"Not only can you <code>pop()</code> data off of the end of an array, you can also <code>push()</code> data onto the end of an array.",
"Push <code>[\"dog\", 3]</code> onto the end of the <code>myArray</code> variable."
],
"tests": [
"assert((function(d){if(d[2] != undefined && d[0] == 'John' && d[1] == 23 && d[2][0] == 'dog' && d[2][1] == 3 && d[2].length == 2){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should now equal <code>[\"John\", 23, [\"dog\", 3]]</code>.');"
],
"challengeSeed": [
"var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];",
"",
"ourArray.pop(); // ourArray now equals [\"Stimpson\", \"J\"]",
"",
"ourArray.push([\"happy\", \"joy\"]); // ourArray now equals [\"Stimpson\", \"J\", [\"happy\", \"joy\"]]",
"",
"var myArray = [\"John\", 23, [\"cat\", 2]];",
"",
"myArray.pop();",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con push()",
"descriptionEs": [
"No sólo se pueden sacar datos del final de un vector con <code>pop()</code>, también puedes empujar (<code>push()</code>) datos al final del vector.",
"Empuja <code>[\"dog\", 3]</code> al final de la variable <code>myArray</code>."
]
},
{
"id": "bg9996c9c69feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Manipulate Arrays With shift()",
"description": [
"<code>pop()</code> always removes the last element of an array. What if you want to remove the first?",
"That's where <code>.shift()</code> comes in. It works just like <code>.pop()</code>, except it removes the first element instead of the last.",
"Use the <code>.shift()</code> function to remove the first item from <code>myArray</code>, assigning the \"shifted off\" value to <code>removedFromMyArray</code>."
],
"tests": [
"assert((function(d){if(d[0] == 23 && d[1][0] == 'dog' && d[1][1] == 3 && d[2] == undefined){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should now equal <code>[23, [\"dog\", 3]]</code>.');",
2015-11-20 23:39:25 -08:00
"assert((function(d){if(d === 'John' && typeof removedFromMyArray === 'string'){return true;}else{return false;}})(removedFromMyArray), 'message: <code>removedFromMyArray</code> should contain <code>\"John\"</code>.');"
],
"challengeSeed": [
"var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];",
"",
"var removedFromOurArray = ourArray.shift(); // removedFromOurArray now equals \"Stimpson\" and ourArray now equals [\"J\", [\"cat\"]].",
"",
"var myArray = [\"John\", 23, [\"dog\", 3]];",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
"var removedFromMyArray;"
],
"tail":[
"(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con shift()",
"descriptionEs": [
"<code>pop()</code> siempre elimina el último elemento de un vector. ¿Qué pasa si quieres quitar el primero?",
"Ahí es donde entra <code>.shift()</code>. Funciona igual que <code>.pop ()</code>, excepto que elimina el primer elemento en lugar del pasado. ",
"Usa la función <code>.shift()</code> para eliminar el primer elemento de <code>myArray</code>, y el elemento que saques asignalo a <code>removedFromMyArra</code>"
]
},
{
"id": "bg9997c9c69feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Manipulate Arrays With unshift()",
"description": [
"Not only can you <code>shift</code> elements off of the beginning of an array, you can also <code>unshift</code> elements onto the beginning of an array.",
"<code>unshift()</code> works exactly like <code>push()</code>, but instead of adding the element at the end of the array, <code>unshift()</code> adds the element at the beginning of the array.",
"Add <code>\"Paul\"</code> onto the beginning of the <code>myArray</code> variable using <code>unshift()</code>."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(d){if(typeof d[0] === \"string\" && d[0].toLowerCase() == 'paul' && d[1] == 23 && d[2][0] != undefined && d[2][0] == 'dog' && d[2][1] != undefined && d[2][1] == 3){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should now have [\"Paul\", 23, [\"dog\", 3]]).');"
],
"challengeSeed": [
"var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];",
"",
"ourArray.shift(); // ourArray now equals [\"J\", [\"cat\"]]",
"",
"ourArray.unshift(\"happy\"); // ourArray now equals [\"happy\", \"J\", [\"cat\"]]",
"",
"var myArray = [\"John\", 23, [\"dog\", 3]];",
"",
"myArray.shift();",
2015-08-15 13:57:44 -07:00
"",
"// Only change code below this line.",
"",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
"(function(y, z){return 'myArray = ' + JSON.stringify(y);})(myArray);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con unshift()",
"descriptionEs": [
"No sólo se puedes <code>correr</code> (shift) elementos del comienzo de un vector, también puedes <code>descorrerlos</code> (unshift) al comienzo.",
"<code>unshift()</code> funciona exactamente igual que <code>push()</code>, pero en lugar de añadir el elemento al final del vector, <code>unshift()</code> añade el elemento al comienzo del vector. ",
"Añade <code>\"Paul\"</code> al comienzo de la variable <code>myArray</code> usando <code>unshift()</code>."
]
},
{
"id": "bg9997c9c89feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Write Reusable JavaScript with Functions",
"description": [
"In JavaScript, we can divide up our code into reusable parts called functions.",
"Here's an example of a function:",
"<code>function functionName(a, b) {</code>",
"<code>&nbsp;&nbsp;return a + b;</code>",
"<code>}</code>",
"After writing the above lines in our code, we can then pass values to our function and the result following the <code>return</code> statement will be returned.",
"For example, we can pass numbers <code>4</code> and <code>2</code> by “calling” the function later in our code like this: <code>functionName(4, 2)</code>.",
"In this example, the function will return the number <code>6</code> as this is the result of <code>4 + 2</code>.",
"Create and call a function called <code>myFunction</code> that returns the sum of <code>a</code> and <code>b</code>."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(){if(typeof f !== \"undefined\" && f === a + b){return true;}else{return false;}})(), 'message: Your function should return the value of <code>a + b</code>.');"
],
"challengeSeed": [
"var a = 4;",
"var b = 5;",
"",
"function ourFunction(a, b) {",
" return a - b;",
"}",
"",
"// Only change code below this line.",
"",
"",
"",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof myFunction !== \"undefined\"){",
"var f=myFunction(a,b);",
2015-08-27 22:18:09 +02:00
"(function(){return f;})();",
"}"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Escribe código Javascript reutilizable con funciones",
"descriptionEs": [
"En JavaScript, podemos dividir nuestro código en partes reutilizables llamadas funciones.",
"He aquí un ejemplo de una función:",
"<code>function nombreDeFuncion(a, b) {</code>",
"<code>& nbsp; & nbsp; return a + b;</code>",
"<code>}</code>",
"Después de escribir las líneas anteriores en nuestro código, podemos pasar valores a nuestra función y el resultado que sigue a la instrucción <code>return</code> será retornado.",
"Por ejemplo, podemos pasar los números <code>4</code> y <code>2</code> al \"llamar\" la función más adelante en nuestro código, así: <code>nombreDeFuncion(4, 2)</ code >. ",
"En este ejemplo, la función devolverá el número <code>6</code>, ya que es el resultado de <code>4 + 2</code>.",
"Crea y llama una función de nombre <code>myFunction</code> que devuelva la suma de <code>a</code> y <code>b</code>."
]
},
{
"id": "bg9998c9c99feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Build JavaScript Objects",
"description": [
"You may have heard the term <code>object</code> before.",
"Objects are similar to <code>arrays</code>, except that instead of using indexes to access and modify their data, you access the data in objects through what are called <code>properties</code>.",
"Here's a sample object:",
"<code>var cat = {</code>",
"<code>&nbsp;&nbsp;\"name\": \"Whiskers\",</code>",
"<code>&nbsp;&nbsp;\"legs\": 4,</code>",
"<code>&nbsp;&nbsp;\"tails\": 1,</code>",
"<code>&nbsp;&nbsp;\"enemies\": [\"Water\", \"Dogs\"]</code>",
"<code>};</code>",
"</code>",
"Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.",
"Let's try to make an object that represents a dog called <code>myDog</code> which contains the properties <code>\"name\"</code> (a string), <code>\"legs\"</code>, <code>\"tails\"</code> and <code>\"friends\"</code>.",
"You can set these object properties to whatever values you want, as long <code>\"name\"</code> is a string, <code>\"legs\"</code> and <code>\"tails\"</code> are numbers, and <code>\"friends\"</code> is an array."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof z.name === \"string\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>name</code> and it should be a <code>string</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"legs\") && z.legs !== undefined && typeof z.legs === \"number\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>legs</code> and it should be a <code>number</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"tails\") && z.tails !== undefined && typeof z.tails === \"number\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>tails</code> and it should be a <code>number</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"friends\") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>friends</code> and it should be an <code>array</code>.');"
],
"challengeSeed": [
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"everything!\"]",
"};",
"",
2015-08-15 13:57:44 -07:00
"// Only change code below this line.",
"",
"var myDog = {",
"",
"",
"",
"",
"};",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
2015-10-28 05:13:49 -07:00
"",
2015-08-27 22:18:09 +02:00
"(function(z){return z;})(myDog);"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Construye objetos en JavaScript",
"descriptionEs": [
"Es posible que haya oído el término <code>objeto</code> antes.",
"Los objetos son similares a los <code>vectores</code>, excepto que en lugar de utilizar los índices para acceder y modificar sus datos, pueden accederse mediante lo que se llama <code>propiedades</code>.",
"Esto es un objeto de ejemplo:",
"<code>var cat = {</code>",
"<code>&nbsp;&nbsp;\"name\": \"Whiskers\",</code>",
"<code>&nbsp;&nbsp;\"legs\": 4,</code>",
"<code>&nbsp;&nbsp;\"tails\": 1,</code>",
"<code>&nbsp;&nbsp;\"enemies\": [\"Water\", \"Dogs\"]</code>",
"<code>};</code>",
"Los objetos son útiles para almacenar datos de manera estructurada, y pueden representar objetos del mundo real, como un gato.",
"Vamos a tratar de hacer un objeto que representa un perro, lo llamaremos <code>mydog</code> y contendrá las propiedades <code>\"name\"</code> (una cadena con el nombre), <code>\"legs\"</code> (piernas), <code>\"tails\"</code> (colas) y <code>\"friends\" (amigos)</code>. ",
"Podrás establecer estas propiedades del objeto en los valores que desees, siempre y cuando <code>\"name\"</code> sea una cadena, <code>\"legs\"</code> y <code>\"tails\"</code> sean números, y <code>\"friends\"</code> sea un vector."
]
},
{
"id": "bg9999c9c99feddfaeb9bdef",
"title": "Update the Properties of a JavaScript Object",
"description": [
"After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable.",
"For example, let's look at <code>ourDog</code>:",
"<code>var ourDog = {</code>",
"<code>&nbsp;&nbsp;\"name\": \"Camper\",</code>",
"<code>&nbsp;&nbsp;\"legs\": 4,</code>",
"<code>&nbsp;&nbsp;\"tails\": 1,</code>",
"<code>&nbsp;&nbsp;\"friends\": [\"everything!\"]</code>",
"<code>};</code>",
"Since he's a particularly happy dog, let's change his name to \"Happy Camper\". Here's how we update his object's name property:",
"<code>ourDog.name = \"Happy Camper\";</code>",
"Now when we run <code>return ourDog.name</code>, instead of getting \"Camper\", we'll get his new name, \"Happy Camper\".",
"Let's update the <code>myDog</code> object's name property. Let's change her name from \"Coder\" to \"Happy Coder\"."
],
"tests": [
"assert(/happy coder/gi.test(myDog.name), 'message: Update <code>myDog</code>&apos;s <code>\"name\"</code> property to equal \"Happy Coder\".');"
],
"challengeSeed": [
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"everything!\"]",
"};",
"",
"ourDog.name = \"Happy Camper\";",
2015-07-10 00:56:30 +01:00
"",
"var myDog = {",
" \"name\": \"Coder\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"Free Code Camp Campers\"]",
2015-07-10 00:56:30 +01:00
"};",
2015-08-15 13:57:44 -07:00
"",
"// Only change code below this line.",
"",
"",
"",
"// Only change code above this line.",
2015-07-10 00:56:30 +01:00
"",
2015-08-27 22:18:09 +02:00
"(function(z){return z;})(myDog);"
2015-07-10 00:56:30 +01:00
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Actualiza las propiedades de un objeto en JavaScript",
"descriptionEs": [
"Después de que hayas creado un objeto de JavaScript, puedes actualizar sus propiedades en cualquier momento, tal y como harías con cualquier otra variable.",
"Por ejemplo, echemos un vistazo a <code>ourDog</code>:",
"<code>var ourDog = {</code>",
"<code>&nbsp;&nbsp;\"name\": \"Camper\",</code>",
"<code>&nbsp;&nbsp;\"legs\": 4,</code>",
"<code>&nbsp;&nbsp;\"tails\": 1,</code>",
"<code>&nbsp;&nbsp;\"friends\": [\"everything!\"]</code>",
"<code>};</code>",
"Dado que es un perro particularmente feliz, vamos a cambiar su nombre a \"Happy Camper\". Así es como actualizamos la propiedad nombre del objeto: ",
"<code>ourDog.name = \"Happy Camper\";</code>",
"Ahora, cuando ejecutemos <code>return ourDog.name</code>, en lugar de obtener \"Camper\", vamos a recibir su nuevo nombre, \"Happy Camper\".",
"Vamos a actualizar la propiedad del objeto <code>mydog</code>. Cambiemos su nombre de \"Coder\" a \"Happy Coder\"."
]
2015-07-10 00:56:30 +01:00
},
{
"id": "bg9999c9c99feedfaeb9bdef",
"title": "Add New Properties to a JavaScript Object",
"description": [
"You can add new properties to existing JavaScript objects the same way you would modify them.",
"Here's how we would add a <code>\"bark\"</code> property to <code>ourDog</code>:",
"<code>ourDog.bark = \"bow-wow\";</code>",
"Now when we run <code>return ourDog.bark</code>, we'll get his bark, \"bow-wow\".",
"Let's add a <code>\"bark\"</code> property to <code>myDog</code> and set it to a dog sound, such as \"woof\"."
],
"tests": [
"assert(myDog.bark !== undefined, 'message: Add the property <code>\"bark\"</code> to <code>myDog</code>.');"
],
"challengeSeed": [
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"everything!\"]",
"};",
"",
"ourDog.bark = \"bow-wow\";",
"",
"var myDog = {",
" \"name\": \"Happy Coder\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"Free Code Camp Campers\"]",
"};",
"",
"// Only change code below this line.",
"",
"",
"",
"// Only change code above this line.",
"",
"(function(z){return z;})(myDog);"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Añade nuevas propiedades a un objeto JavaScript",
"descriptionEs": [
"Puedes añadir nuevas propiedades a objetos existente de la misma forma que usarías para modificarlos.",
"Así es como añadimos una propiedad <code>\"bark\"</code> (ladra) a nuestro objeto <code>ourDog</code>:",
"<code>ourDog.bark = \"bow-wow\";</code>",
"Ahora, cuando ejecutemos <code>return ourDog.bark</code>, vamos a recbir su ladrido, \" bow-wow \".",
"Vamos a añadir una propiedad <code>ladra</code> a <code>myDog</code> y a ponerle un sonido de perro, tal como \"woof\"."
]
},
{
"id": "bg9999c9c99fdddfaeb9bdef",
"title": "Delete Properties from a JavaScript Object",
"description": [
"We can also delete properties from objects like this:",
"<code>delete ourDog.bark;</code>",
"Let's delete the <code>\"tails\"</code> property from <code>myDog</code>."
],
"tests": [
"assert(myDog.tails === undefined, 'message: Delete the property <code>\"tails\"</code> from <code>myDog</code>.');"
],
"challengeSeed": [
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
" \"tails\": 1,",
2015-10-28 05:13:49 -07:00
" \"friends\": [\"everything!\"],",
" \"bark\": \"bow-wow\"",
"};",
"",
"delete ourDog.bark;",
"",
"var myDog = {",
" \"name\": \"Happy Coder\",",
" \"legs\": 4,",
" \"tails\": 1,",
2015-10-28 05:13:49 -07:00
" \"friends\": [\"Free Code Camp Campers\"],",
" \"bark\": \"woof\"",
"};",
"",
"// Only change code below this line.",
"",
"",
"",
"// Only change code above this line.",
"",
"(function(z){return z;})(myDog);"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Elimina propiedades de un objeto JavaScript",
"descriptionEs": [
"También podemos eliminar propiedades de los objetos de esta manera:",
"<code>delete ourDog.bark;</code>",
"Borremos la propiedad <code>\"tails\"</code> de <code>myDog</code>."
]
},
{
"id": "cf1111c1c11feddfaeb5bdef",
2015-08-07 23:37:32 -07:00
"title": "Iterate with JavaScript For Loops",
"description": [
"You can run the same code multiple times by using a loop.",
"The most common type of JavaScript loop is called a \"for loop\" because it runs \"for\" a specific number of times.",
"For loops are declared with three optional expressions seperated by semicolons:",
"<code>for ([initialization]; [condition]; [final-expression])</code>",
"The <code>initialization</code> statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.",
"The <code>condition</code> statement is evaluated at the beginning of every loop iteration and will continue as long as it evalutes to <code>true</code>. When <code>condition</code> is <code>false</code> at the start of the iteration, the loop will stop executing. This means if <code>condition</code> starts as <code>false</code>, your loop will never execute.",
"The <code>final-expression</code> is executed at the end of each loop iteration, prior to the next <code>condition</code> check and is usually used to increment or decrement your loop counter.",
"In the following example we initialize with <code>i = 0</code> and iterate while our condition <code>i < 5</code> is true. We'll increment <code>i</code> by <code>1</code> in each loop iteration with <code>i++</code> as our <code>final-expression</code>.",
"<code>var ourArray = [];</code>",
"<code>for (var i = 0; i < 5; i++) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> will now contain <code>[0,1,2,3,4]</code>.",
"Let's use a <code>for</code> loop to work to push the values 1 through 5 onto <code>myArray</code>."
2015-07-10 00:56:30 +01:00
],
"tests": [
"assert(editor.getValue().match(/for\\s*\\(/g).length > 1, 'message: You should be using a <code>for</code> loop for this.');",
"assert.deepEqual(myArray, [1,2,3,4,5], 'message: <code>myArray</code> should equal <code>[1,2,3,4,5]</code>.');"
2015-07-10 00:56:30 +01:00
],
"challengeSeed": [
"var ourArray = [];",
2015-10-28 05:13:49 -07:00
"",
"for (var i = 0; i < 5; i++) {",
2015-08-21 22:01:03 +01:00
" ourArray.push(i);",
"}",
2015-10-28 05:13:49 -07:00
"",
2015-07-10 00:56:30 +01:00
"var myArray = [];",
"",
"// Only change code below this line.",
"",
2015-10-28 05:13:49 -07:00
"",
"",
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}",
2015-07-10 00:56:30 +01:00
""
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Iterar con JavaScript en ciclos",
"descriptionEs": [
"Puede ejecutar el mismo código varias veces mediante el uso de un ciclo.",
"El tipo más común de bucle de JavaScript se llama \"ciclo for\"porque se ejecuta \"por\" (for) un número específico de veces.",
"Los ciclos for se declaran con tres expresiones opcionales separadas por punto y coma:",
"<code>for ([inicialización]; [condición]; [expresión-final])</code>",
"La <code>inicialización</code> se ejecuta sólo una vez antes de que empiece el ciclo. Normalmente se utiliza para definir e inicializar su variable de ciclo. ",
"La expresión <code>condición</code> se evalúa al principio de cada iteración del ciclo y continuará en el ciclo siempre y cuando sea verdadera (<code>true</code>). Cuando la <code>condición</code> sea falsa (<code>false</code>) al comienzo de la iteración, se detendrá la ejecución del ciclo. Esto significa que si la <code>condición</code> inicia en el valor falso <code>false</code>, el ciclo no se ejecutará. ",
"La <code>expresión final</code> se ejecuta al final de cada repetición del ciclo, antes del siguiente chequeo de la <code>condición</code> y se utiliza generalmente para aumentar o disminuir el contador del ciclo.",
"En el siguiente ejemplo inicializamos con <code>i = 0</code> e iteramos mientras nuestra condición <code>i <5</code> sea verdadera. Vamos a incrementar <code>i</code> en <code>1</code> en cada iteración del ciclo con <code>i++</code> como nuestra <code>expresión final</code>. ",
"<code>var ourArray = [];</code>",
"<code>for (var i = 0; i < 5; i++) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> ahora contendrá <code>[0,1,2,3,4]</code>.",
"Vamos a utilizar un ciclo <code>for</code> para empujar los valores del 1 al 5 en <code>myArray</code>."
]
2015-07-10 00:56:30 +01:00
},
{
"id": "56104e9e514f539506016a5c",
"title": "Iterate Odd Numbers With a For Loop",
"description": [
"For loops don't have to iterate one at a time. By changing our <code>final-expression</code>, we can count by even numbers.",
"We'll start at <code>i = 0</code> and loop while <code>i < 10</code>. We'll increment <code>i</code> by 2 each loop with <code>i += 2</code>.",
"<code>var ourArray = [];</code>",
"<code>for (var i = 0; i < 10; i += 2) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> will now contain <code>[0,2,4,6,8]</code>.",
2015-10-28 05:13:49 -07:00
"Let's change our <code>initialization</code> and <code>final-expression</code> so we can count by odd numbers.",
"Push the odd numbers from 1 through 9 to <code>myArray</code> using a <code>for</code> loop."
],
"tests": [
"assert(editor.getValue().match(/for\\s*\\(/g).length > 1, 'message: You should be using a <code>for</code> loop for this.');",
"assert.deepEqual(myArray, [1,3,5,7,9], 'message: <code>myArray</code> should equal <code>[1,3,5,7,9]</code>.');"
],
"challengeSeed": [
"var ourArray = [];",
2015-10-28 05:13:49 -07:00
"",
"for (var i = 0; i < 10; i += 2) {",
" ourArray.push(i);",
"}",
2015-10-28 05:13:49 -07:00
"",
"var myArray = [];",
"",
"// Only change code below this line.",
"",
2015-10-28 05:13:49 -07:00
"",
"",
"// Only change code above this line.",
2015-10-28 05:13:49 -07:00
"",
2015-11-20 23:39:25 -08:00
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}",
""
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Itera por los números pares con un ciclo for",
"descriptionEs": [
"Los ciclos <code>for</code> no siempre iteran incrementado de a uno. Cambiando nuestra <code>expresión final</code>, podemos contar los números pares.",
"Vamos a empezar con <code>i = 0</code> e iterar mientras <code>i <10</code>. Vamos a incrementar <code>i</code> de a 2 en cada iteración <code>i + = 2</code>. ",
"<code>var ourArray = [];</code>",
"<code>for (var i = 0; i < 10; i += 2) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> ahora contendrá <code>[0,2,4,6,8]</code>.",
"Vamos a cambiar nuestra <code>inicialización</code> y <code>expresión final</code> para que podamos contar los números impares.",
"Empuja los números impares del 1 al 9 en <code>myArray</code> utilizando un ciclo <code>for</code>."
]
},
{
"id": "56105e7b514f539506016a5e",
"title": "Count Backwards With a For Loop",
"description": [
"A for loop can also count backwards, so long as we can define the right conditions.",
"In order to count backwards by twos, we'll need to change our <code>initialization</code>, <code>condition</code>, and <code>final-expression</code>.",
"We'll start at <code>i = 10</code> and loop while <code>i > 0</code>. We'll decrement <code>i</code> by 2 each loop with <code>i -= 2</code>.",
"<code>var ourArray = [];</code>",
"<code>for (var i = 10; i > 0; i -= 2) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> will now contain <code>[10,8,6,4,2]</code>.",
"Let's change our <code>initialization</code> and <code>final-expression</code> so we can count backward by twos by odd numbers.",
"Push the odd numbers from 9 through 1 to <code>myArray</code> using a <code>for</code> loop."
],
"tests": [
"assert(editor.getValue().match(/for\\s*\\(/g).length > 1, 'message: You should be using a <code>for</code> loop for this.');",
"assert.deepEqual(myArray, [9,7,5,3,1], 'message: <code>myArray</code> should equal <code>[9,7,5,3,1]</code>.');"
],
"challengeSeed": [
"var ourArray = [];",
2015-10-28 05:13:49 -07:00
"",
"for (var i = 10; i > 0; i -= 2) {",
" ourArray.push(i);",
"}",
2015-10-28 05:13:49 -07:00
"",
"var myArray = [];",
"",
"// Only change code below this line.",
"",
2015-10-28 05:13:49 -07:00
"",
""
],
"tail": [
2015-11-20 23:39:25 -08:00
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Cuenta hacia atrás con un ciclo for",
"descriptionEs": [
"Un ciclo también puede contar hacia atrás, siempre y cuando definamos las condiciones adecuadas.",
"Para contar hacia atrás de dos en dos, tendremos que cambiar nuestra <code>inicialización</code>, la <code>condición</code> y la <code>última-expresión</code>.",
"Vamos a empezar con <code>i = 10</code> e iteraremos mientras <code>i > 0</code>. Vamos a decrementar <code>i</code> de a 2 por cada iteración con <code>i -= 2</code>. ",
"<code>var ourArray = [];</code>",
"<code>for (var i = 10; i > 0; i -= 2) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> ahora contendrá <code>[10,8,6,4,2]</code>.",
"Vamos a cambiar nuestra <code>inicialización</code> y la <code>expresión final</code> para que podamos contar hacia atrás de dos en dos pero números impares.",
"Empuja los números impares del 9 a 1 en <code>myArray</code> utilizando un ciclo <code>for</code>."
]
},
2015-07-10 00:56:30 +01:00
{
"id": "cf1111c1c11feddfaeb1bdef",
2015-08-07 23:37:32 -07:00
"title": "Iterate with JavaScript While Loops",
"description": [
"You can run the same code multiple times by using a loop.",
2015-08-18 00:17:56 -04:00
"Another type of JavaScript loop is called a \"while loop\", because it runs \"while\" something is true and stops once that something is no longer true.",
"<code>var ourArray = [];</code>",
"<code>var i = 0;</code>",
"<code>while (i < 5) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>&nbsp;&nbsp;i++;</code>",
"<code>}</code>",
2015-10-28 05:13:49 -07:00
"Let's try getting a while loop to work by pushing values to an array.",
"Push the numbers 0 through 4 to <code>myArray</code> using a <code>while</code> loop."
2015-07-10 00:56:30 +01:00
],
"tests": [
"assert(editor.getValue().match(/while/g), 'message: You should be using a <code>while</code> loop for this.');",
"assert.deepEqual(myArray, [0,1,2,3,4], 'message: <code>myArray</code> should equal <code>[0,1,2,3,4]</code>.');"
2015-07-10 00:56:30 +01:00
],
"challengeSeed": [
2015-07-10 00:56:30 +01:00
"var myArray = [];",
2015-10-28 05:13:49 -07:00
"",
"// Only change code below this line.",
"",
2015-10-28 05:13:49 -07:00
"",
2015-07-10 00:56:30 +01:00
"",
"// Only change code above this line.",
"",
2015-11-20 23:39:25 -08:00
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}",
2015-07-10 00:56:30 +01:00
""
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Iterar con JavaScript con ciclos while",
"descriptionEs": [
"Puede ejecutar el mismo código varias veces mediante el uso de un ciclo.",
"Otro tipo de ciclo de JavaScript se llama un ciclo \"while\", ya que se ejecuta, \"mientras que\" algo sea cierto y se detiene una vez que ya no sea así.",
"<code>var ourArray = [];</code>",
"<code>var i = 0;</code>",
"<code>while(i < 5) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>&nbsp;&nbsp;i++;</code>",
"<code>}</code>",
"Intentemos que un ciclo <code>while</code> empuje valores en un vector.",
"Empuja los números de 0 a 4 para <code>myArray</code> utilizando un ciclo <code>while</code>."
]
2015-07-10 00:56:30 +01:00
},
{
"id": "cf1111c1c11feddfaeb9bdef",
2015-08-07 23:37:32 -07:00
"title": "Generate Random Fractions with JavaScript",
"description": [
2015-08-18 00:22:33 -04:00
"Random numbers are useful for creating random behavior.",
"JavaScript has a <code>Math.random()</code> function that generates a random decimal number between 0 and 1.",
2015-10-28 05:13:49 -07:00
"Change <code>myFunction</code> to return a random number instead of returning <code>0</code>.",
"Note that you can return a function, just like you would return a variable or value."
],
"tests": [
2015-11-20 23:39:25 -08:00
"assert(typeof myFunction() === \"number\", 'message: <code>myFunction</code> should return a random number.');",
"assert((myFunction()+''). match(/\\./g), 'message: The number returned by <code>myFunction</code> should be a decimal.');",
2015-10-28 05:13:49 -07:00
"assert(editor.getValue().match(/Math\\.random/g).length >= 0, 'message: You should be using <code>Math.random</code> to generate the random decimal number.');"
],
"challengeSeed": [
"function myFunction() {",
2015-10-28 05:13:49 -07:00
"",
2015-08-15 13:57:44 -07:00
" // Only change code below this line.",
"",
2015-08-27 22:18:09 +02:00
" return 0;",
2015-08-15 13:57:44 -07:00
"",
2015-09-13 23:26:03 -07:00
" // Only change code above this line.",
2015-07-10 00:56:30 +01:00
"}",
"",
2015-08-27 22:18:09 +02:00
"(function(){return myFunction();})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Generar fracciones al azar con JavaScript",
"descriptionEs": [
"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.",
"Cambia <code>myFunction</code> para que devuelva un número al azar en lugar de devolver <code>0</code>.",
"Ten en cuenta que puedes retornar lo retornado por una función, igual que harías para devolver una variable o valor."
]
},
{
"id": "cf1111c1c12feddfaeb1bdef",
2015-08-07 23:37:32 -07:00
"title": "Generate Random Whole Numbers with JavaScript",
"description": [
"It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.",
"First, let's use <code>Math.random()</code> to generate a random decimal.",
"Then let's multiply this random decimal by 20.",
"Finally, let's use another function, <code>Math.floor()</code> to round the number down to its nearest whole number.",
"This technique will gives us a whole number between 0 and 19.",
"Note that because we're rounding down, it's impossible to actually get 20.",
"Putting everything together, this is what our code looks like:",
"<code>Math.floor(Math.random() * 20);</code>",
"See how <code>Math.floor</code> takes <code>(Math.random() * 20)</code> as its argument? That's right - you can pass a function to another function as an argument.",
"Let's use this technique to generate and return a random whole number between 0 and 9."
],
"tests": [
"assert(editor.getValue().match(/var\\srandomNumberBetween0and19\\s=\\sMath.floor\\(Math.random\\(\\)\\s\\*\\s20\\);/).length == 1, 'message: The first line of code should not be changed.');",
2015-11-20 23:39:25 -08:00
"assert(typeof myFunction() === \"number\" && (function(){var r = myFunction();return Math.floor(r) === r;})(), 'message: The result of <code>myFunction</code> should be a whole number.');",
"assert(editor.getValue().match(/Math.random/g).length > 1, 'message: You should be using <code>Math.random</code> to generate a random number.');",
"assert(editor.getValue().match(/\\(\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\*\\s*?10\\s*?\\)/g) || editor.getValue().match(/\\(\\s*?10\\s*?\\*\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\)/g), 'message: You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.');",
"assert(editor.getValue().match(/Math.floor/g).length > 1, 'message: You should use <code>Math.floor</code> to remove the decimal part of the number.');"
2015-07-10 00:56:30 +01:00
],
"challengeSeed": [
"var randomNumberBetween0and19 = Math.floor(Math.random() * 20);",
"",
"function myFunction() {",
2015-08-15 13:57:44 -07:00
"",
" // Only change code below this line.",
"",
2015-08-27 22:18:09 +02:00
" return Math.random();",
2015-08-15 13:57:44 -07:00
"",
" // Only change code above this line.",
"}"
],
"tail": [
2015-08-27 22:18:09 +02:00
"(function(){return myFunction();})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Genera números aleatorios enteros con JavaScript",
"descriptionEs": [
"Es muy bueno que podamos generar números decimales al azar, pero es aún más útil si lo utilizamos para generar números enteros aleatorios.",
"En primer lugar, vamos a usar <code>Math.random()</code> para generar un decimal aleatorio.",
"Entonces vamos a multiplicar este decimal azar por 20.",
"Por último, vamos a usar otra función, <code>Math.floor()</code> para redondear el número hasta su número entero más próximo.",
"Esta técnica nos da un número entero entre 0 y 19.",
"Tenga en cuenta que debido a que estamos redondeando, es imposible obtener 20.",
"Poniendo todo junto, así es como se ve nuestro código:",
"<code>Math.floor(Math.random() * 20);</code>",
"¿Ves como <code>Math.floor</code> toma <code>(Math.random() * 20)</code> como su argumento? Así es - puedes pasar el resultado de un función como argumento de otra función.",
"usemos esta técnica para generar y devolver un número entero aleatorio entre 0 y 9."
]
},
{
"id": "cf1111c1c12feddfaeb2bdef",
2015-08-07 23:37:32 -07:00
"title": "Generate Random Whole Numbers within a Range",
"description": [
"Instead of generating a random number between zero and a given number like we did before, we can generate a random number that falls within a range of two specific numbers.",
"To do this, we'll define a minimum number <code>min</code> and a maximum number <code>max</code>.",
2015-10-28 05:13:49 -07:00
"Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:",
2015-09-13 23:26:03 -07:00
"<code>Math.floor(Math.random() * (max - min + 1)) + min</code>",
"Define two variables: <code>myMin</code> and <code>myMax</code>, and set them both equal to numbers.",
"Then create a function called <code>myFunction</code> that returns a random number that's greater than or equal to <code>myMin</code>, and is less than or equal to <code>myMax</code>."
],
"tests": [
"assert(myFunction() >= myMin, 'message: The random number generated by <code>myFunction</code> should be greater than or equal to your minimum number, <code>myMin</code>.');",
"assert(myFunction() <= myMax, 'message: The random number generated by <code>myFunction</code> should be less than or equal to your maximum number, <code>myMax</code>.');",
"assert(myFunction() % 1 === 0 , 'message: The random number generated by <code>myFunction</code> should be an integer, not a decimal.');",
2015-10-28 05:13:49 -07:00
"assert((function(){if(editor.getValue().match(/myMax/g).length > 1 && editor.getValue().match(/myMin/g).length > 2 && editor.getValue().match(/Math.floor/g) && editor.getValue().match(/Math.random/g)){return true;}else{return false;}})(), 'message: <code>myFunction()</code> should use use both <code>myMax</code> and <code>myMin</code>, and return a random number in your range.');"
],
"challengeSeed": [
"var ourMin = 1;",
"",
"var ourMax = 9;",
"",
"function ourFunction() {",
"",
" return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;",
"",
"}",
"",
2015-10-28 05:13:49 -07:00
"// Only change code below this line.",
"",
2015-10-28 05:13:49 -07:00
"var myMin;",
"",
2015-10-28 05:13:49 -07:00
"var myMax;",
"",
2015-10-28 05:13:49 -07:00
"function myFunction() {",
"",
2015-10-28 05:13:49 -07:00
" return;",
"",
2015-10-28 05:13:49 -07:00
"}",
"",
2015-08-15 13:57:44 -07:00
"// Only change code above this line.",
"",
"",
2015-08-27 22:18:09 +02:00
"(function(){return myFunction();})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Genera números aleatorios enteros dentro de un rango",
"descriptionEs": [
"En lugar de generar un número aleatorio entre cero y un número dado como lo hicimos antes, podemos generar un número aleatorio que caiga dentro de un rango de dos números específicos.",
"Para ello, vamos a definir un número mínimo <code>min</code> y un número máximo <code>max</code>.",
"He aquí la fórmula que utilizaremos. Tómate un momento para leer y tratar de entender lo que el código está haciendo: ",
"<code>Math.floor(Math.random() * (max - min + 1)) + min</code>",
"Definir dos variables: <code>myMin</code> y <code>myMax</code>, y asignales valores enteros.",
"A continuación, crea una función llamada <code>myFunction</code> que devuelva un número aleatorio mayor o igual a <code>myMin</code>, y menor o igual a <code>myMax</code>. "
]
},
{
"id": "cf1111c1c12feddfaeb3bdef",
2015-09-13 23:26:03 -07:00
"title": "Use Conditional Logic with If and Else Statements",
"description": [
2015-09-13 23:26:03 -07:00
"We can use <code>if</code> statements in JavaScript to only execute code if a certain condition is met.",
"<code>if</code> statements require some sort of boolean condition to evaluate.",
"For example:",
"<code>var x = 1;</code>",
"<code>if (x === 2) {</code>",
"<code>&nbsp;&nbsp;return 'x is 2';</code>",
2015-09-13 23:26:03 -07:00
"<code>} else {</code>",
"<code>&nbsp;&nbsp;return 'x is not 2';</code>",
2015-08-17 16:34:45 -04:00
"<code>}</code>",
"Let's use <code>if</code> and <code>else</code> statements to make a coin-flip game.",
2015-09-13 23:26:03 -07:00
"Create <code>if</code> and <code>else</code> statements to return the string <code>\"heads\"</code> if the flip variable is zero, or else return the string <code>\"tails\"</code> if the flip variable is not zero."
],
"tests": [
2015-10-28 05:13:49 -07:00
"assert(editor.getValue().match(/if/g).length >= 2, 'message: Create a new if statement.');",
"assert(editor.getValue().match(/else/g).length >= 1, 'message: Created a new else statement.');",
"assert((function(){var result = myFunction();if(result === 'heads' || result === 'tails'){return true;} else {return false;}})(), 'message: <code>myFunction</code> should either return <code>heads</code> or <code>tails</code>.');",
"assert((function(){flip = 0; var result = myFunction(); if(result === 'heads'){return true;} else {return false;}})(), 'message: <code>myFunction</code> should return <code>heads</code> when flip equals 0');",
"assert((function(){flip = 1; var result = myFunction(); if(result === 'tails'){return true;} else {return false;}})(), 'message: <code>myFunction</code> should return <code>tails</code> when flip equals 1');"
],
"challengeSeed": [
"var flip = Math.floor(Math.random() * 2);",
2015-10-28 05:13:49 -07:00
"",
"function myFunction() {",
"",
2015-08-15 13:57:44 -07:00
" // Only change code below this line.",
"",
"",
"",
" // Only change code above this line.",
"",
"}",
"",
2015-11-20 23:39:25 -08:00
"var result = myFunction();if(typeof flip !== \"undefined\" && typeof flip === \"number\" && typeof result !== \"undefined\" && typeof result === \"string\"){(function(y,z){return 'flip = ' + y.toString() + ', text = ' + z;})(flip, result);}"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa lógica condicional con instrucciones if y else",
"descriptionEs": [
"Podemos usar instrucciones <code>if</code> (\"if\" es \"si\" en español) en JavaScript para ejecutar código sólo cuando cierta condición se cumpla.",
"Las instrucciones <code>if</code> requieren evaluar algún tipo de condición booleana.",
"Por ejemplo:",
"<code>if (1 === 2) {</code>",
"<code>&nbsp;&nbsp;return true;</code>",
"<code>} else {</code>",
"<code>&nbsp;&nbsp;return false;</code>",
"<code>}</code>",
"Vamos a usar la instrucción <code>if</code> con <code>else</code> (\"else\" puede traducirse como \"de lo contrario\") para hacer un juego de cara o sello.",
"Crea una instrucción <code>if</code> con <code>else</code> que retorne la cadena <code>\"heads\"</code> si la variable <code>flip</code> es cero, o bien que retorne <code >\"tails\"</code> si la variable <code>flip</code> no es cero. "
]
},
{
"id": "cf1111c1c12feddfaeb6bdef",
2015-08-07 23:37:32 -07:00
"title": "Sift through Text with Regular Expressions",
"description": [
2015-08-16 20:14:12 -04:00
"<code>Regular expressions</code> are used to find certain words or patterns inside of <code>strings</code>.",
"For example, if we wanted to find the word <code>the</code> in the string <code>The dog chased the cat</code>, we could use the following <code>regular expression</code>: <code>/the/gi</code>",
"Let's break this down a bit:",
"<code>the</code> is the pattern we want to match.",
"<code>g</code> means that we want to search the entire string for this pattern instead of just the first match.",
2015-08-15 15:56:56 -07:00
"<code>i</code> means that we want to ignore the case (uppercase or lowercase) when searching for the pattern.",
2015-09-13 23:26:03 -07:00
"<code>Regular expressions</code> are written by surrounding the pattern with <code>/</code> symbols.",
"Let's try selecting all the occurrences of the word <code>and</code> in the string <code>Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it</code>.",
"We can do this by replacing the <code>.</code> part of our regular expression with the word <code>and</code>."
],
"tests": [
2015-12-02 18:26:42 -08:00
"assert(myTest==2, 'message: Your <code>regular expression</code> should find two occurrences of the word <code>and</code>.');",
"assert(editor.getValue().match(/\\/and\\/gi/), 'message: Use <code>regular expressions</code> to find the word <code>and</code> in <code>testString</code>.');"
],
"challengeSeed": [
2015-12-02 18:26:42 -08:00
"var myTest = (function() {",
2015-09-13 23:26:03 -07:00
" var testString = \"Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it.\";",
" var expressionToGetSoftware = /software/gi;",
"",
2015-08-15 13:57:44 -07:00
" // Only change code below this line.",
"",
2015-08-30 20:37:32 +05:30
" var expression = /./gi;",
"",
2015-08-15 15:56:56 -07:00
" // Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
" return testString.match(expression).length;",
2015-12-02 18:26:42 -08:00
"})();(function(){return myTest;})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Examina un texto con expresiones regulares",
"descriptionEs": [
"Las <code>expresiones regulares</code> se utilizan para encontrar ciertas palabras o patrones dentro de <code>cadenas</code>.",
"Por ejemplo, si quisiéramos encontrar la palabra <code>el</code> en la cadena <code>El perro persiguió al gato el lunes</code>, podríamos utilizar la siguiente <code>expresión regular</code>: <code>/el/gi</code> ",
"Vamos a dividirla un poco:",
"<code>el</code> es el patrón con el que queremos coincidir.",
"<code>g</code> significa que queremos buscar el patrón en toda la cadena y no sólo la primera ocurrencia.",
"<code>i</code> significa que queremos ignorar la capitalización (en mayúsculas o minúsculas) cuando se busque el patrón.",
"Las <code>expresiones regulares</code> se escriben rodeando el patrón con símbolos de barra <code>/</code>.",
"Vamos a tratar de seleccionar todas las apariciones de la palabra <code>and</code> en la cadena <code>Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it</code>.",
"Podemos hacer esto sustituyendo la parte <code>.</code> de nuestra expresión regular por la palabra <code>and</code>."
]
},
{
"id": "cf1111c1c12feddfaeb7bdef",
2015-08-07 23:37:32 -07:00
"title": "Find Numbers with Regular Expressions",
"description": [
"We can use special selectors in <code>Regular Expressions</code> to select a particular type of value.",
"One such selector is the digit selector <code>\\d</code> which is used to retrieve the numbers in a string.",
"It is used like this: <code>/\\d/g</code>.",
"For numbers this is often written as <code>/\\d+/g</code>, where the <code>+</code> following the digit selector allows this regular expression to match multi-digit numbers.",
"Use the <code>\\d</code> selector to select the number of numbers in the string, allowing for the possibility of multi-digit numbers."
],
"tests": [
"assert(editor.getValue().match(/\\/\\\\d\\+\\//g), 'message: Use the <code>/\\d+/g</code> regular expression to find the numbers in <code>testString</code>.');",
2015-12-02 18:26:42 -08:00
"assert(myTest === 2, 'message: Your regular expression should find two numbers in <code>testString</code>.');"
],
"challengeSeed": [
2015-12-02 18:26:42 -08:00
"var myTest = (function() {",
"",
2015-08-17 22:54:08 -04:00
" var testString = \"There are 3 cats but 4 dogs.\";",
"",
2015-08-15 13:57:44 -07:00
" // Only change code below this line.",
"",
" var expression = /.+/g;",
"",
2015-08-15 15:56:56 -07:00
" // Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
" return testString.match(expression).length;",
"",
2015-12-02 18:26:42 -08:00
"})();(function(){return myTest;})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Encuentra números con expresiones regulares",
"descriptionEs": [
"Podemos usar selectores especiales en las <code>expresiones regulares</code> para seleccionar un determinado tipo de valor.",
"Uno de estos selectores es el de dígitos <code>\\d</code> que se utiliza para hacer coincidir números en una cadena.",
"Se usa así para hacer coincidir un dígito: <code>/\\d/g</code>.",
"Para hacer coincidir números de varios dígtios a menudo se escribe <code>/\\d+/ g </code>, donde el <code>+</code> que sigue al selector de dígito le permite a la expresión regular coincidir con uno o más dígito es decir coincide con números de varios dígitos.",
"Usa el selector <code>\\d</code> para hacer coincidir todos los números de la cadena, permitiendo la posibilidad de hacer coincidir números de varios dígitos."
]
},
{
"id": "cf1111c1c12feddfaeb8bdef",
"title": "Find Whitespace with Regular Expressions",
"description": [
"We can also use regular expression selectors like <code>\\s</code> to find whitespace in a string.",
"The whitespace characters are <code>\" \"</code> (space), <code>\\r</code> (the carriage return), <code>\\n</code> (newline), <code>\\t</code> (tab), and <code>\\f</code> (the form feed).",
"The whitespace regular expression looks like this:",
2015-08-16 04:05:15 -07:00
"<code>/\\s+/g</code>",
"Use it to select all the whitespace characters in the sentence string."
2015-07-10 00:56:30 +01:00
],
"tests": [
"assert(editor.getValue().match(/\\/\\\\s\\+\\//g), 'message: Use the <code>/\\s+/g</code> regular expression to find the spaces in <code>testString</code>.');",
2015-12-02 18:26:42 -08:00
"assert(myTest === 7, 'message: Your regular expression should find seven spaces in <code>testString</code>.');"
],
"challengeSeed": [
2015-12-02 18:26:42 -08:00
"var myTest = (function(){",
2015-08-16 04:05:15 -07:00
" var testString = \"How many spaces are there in this sentence?\";",
"",
2015-08-15 13:57:44 -07:00
" // Only change code below this line.",
"",
" var expression = /.+/g;",
"",
2015-08-16 04:05:15 -07:00
" // Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
" return testString.match(expression).length;",
"",
2015-12-02 18:26:42 -08:00
"})();(function(){return myTest;})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Encuentra espacios en blanco con las expresiones regulares",
"descriptionEs": [
"También podemos utilizar selectores de expresiones regulares como <code>\\s</code> para encontrar un espacio en blanco en una cadena.",
"Los espacios en blanco son <code>\" \"</code> (espacio), <code>\\r</code> (el retorno de carro), <code>\\n</code> (nueva línea), <code>\\t</code> (tabulador), y <code>\\f</code> (el avance de página). ",
"Una expresión regular con el selector de espacios en blanco puede ser:",
"<code>/\\s+/g</code>",
"Se usa para hacer coincidir todos los espacios en blanco en una cadena."
]
2015-07-30 20:58:02 +01:00
},
{
"id": "cf1111c1c13feddfaeb3bdef",
2015-08-07 23:37:32 -07:00
"title": "Invert Regular Expression Matches with JavaScript",
"description": [
"You can invert any match by using the uppercase version of the regular expression selector.",
"For example, <code>\\s</code> will match any whitespace, and <code>\\S</code> will match anything that isn't whitespace.",
"Use <code>/\\S/g</code> to count the number of non-whitespace characters in <code>testString</code>."
],
"tests": [
"assert(editor.getValue().match(/\\/\\\\S\\/g/g), 'message: Use the <code>/\\S/g</code> regular expression to find non-space characters in <code>testString</code>.');",
2015-12-02 18:26:42 -08:00
"assert(myTest === 49, 'message: Your regular expression should find forty nine non-space characters in the <code>testString</code>.');"
],
"challengeSeed": [
2015-12-02 18:26:42 -08:00
"var myTest = (function(){",
" var testString = \"How many non-space characters are there in this sentence?\";",
"",
2015-08-15 13:57:44 -07:00
" // Only change code below this line.",
"",
" var expression = /./g;",
"",
2015-08-16 04:05:15 -07:00
" // Only change code above this line.",
"",
2015-08-27 22:18:09 +02:00
" return testString.match(expression).length;",
2015-12-02 18:26:42 -08:00
"})();(function(){return myTest;})();"
],
2015-08-07 23:37:32 -07:00
"type": "waypoint",
"challengeType": 1,
"nameEs": "Hacer coincidir con una expresión regular invertida",
"descriptionEs": [
"Puedes invertir las coincidencias de un selector usando su versión en mayúsculas.",
"Por ejemplo, <code>\\s</code> coincidirá con cualquier espacio en blanco, mientras que <code>\\S</code> coincidirá con todo lo que no sea espacio en blanco.",
"Usa <code>/\\S/g</code> para contar el número de caracteres que no están en blanco en <code>testString</code>."
]
2015-08-15 13:57:44 -07:00
},
{
"id": "cf1111c1c12feddfaeb9bdef",
2015-08-15 13:57:44 -07:00
"title": "Create a JavaScript Slot Machine",
2015-11-18 12:03:22 -08:00
"isBeta": true,
"description": [
2015-08-15 13:57:44 -07:00
"We are now going to try and combine some of the stuff we've just learned and create the logic for a slot machine game.",
2015-08-16 04:05:15 -07:00
"For this we will need to generate three random numbers between <code>1</code> and <code>3</code> to represent the possible values of each individual slot.",
2015-08-15 13:57:44 -07:00
"Store the three random numbers in <code>slotOne</code>, <code>slotTwo</code> and <code>slotThree</code>.",
"Generate the random numbers by using the system we used earlier (an explanation of the formula can be found <a href=\"https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Waypoint-Generate-Random-Whole-Numbers-within-a-Range#explanation\">here</a>):",
2015-08-16 04:05:15 -07:00
"<code>Math.floor(Math.random() * (3 - 1 + 1)) + 1;</code>"
2015-08-15 13:57:44 -07:00
],
"tests": [
"assert(typeof runSlots($(\".slot\"))[0] === \"number\" && runSlots($(\".slot\"))[0] > 0 && runSlots($(\".slot\"))[0] < 4, 'message: <code>slotOne</code> should be a random number.');",
"assert(typeof runSlots($(\".slot\"))[1] === \"number\" && runSlots($(\".slot\"))[1] > 0 && runSlots($(\".slot\"))[1] < 4, 'message: <code>slotTwo</code> should be a random number.');",
"assert(typeof runSlots($(\".slot\"))[2] === \"number\" && runSlots($(\".slot\"))[2] > 0 && runSlots($(\".slot\"))[2] < 4, 'message: <code>slotThree</code> should be a random number.');",
"assert((function(){if(code.match(/Math\\.floor\\(\\s?Math\\.random\\(\\)\\s?\\*\\s?\\(\\s?3\\s?\\-\\s?1\\s?\\+\\s?1\\s?\\)\\s?\\)\\s?\\+\\s?1/gi) !== null){return code.match(/slot.*?=.*?\\(.*?\\).*?/gi).length >= 3;}else{return false;}})(), 'message: You should have used <code>Math.floor(Math.random() * (3 - 1 + 1)) + 1;</code> three times to generate your random numbers.');"
2015-08-15 13:57:44 -07:00
],
"challengeSeed": [
2015-08-15 13:57:44 -07:00
"fccss",
" function runSlots() {",
2015-08-15 13:57:44 -07:00
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
2015-08-16 04:05:15 -07:00
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
2015-08-15 13:57:44 -07:00
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
" ",
" if (slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined) {",
2015-08-15 13:57:44 -07:00
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
" }",
2015-11-09 11:56:14 +05:30
" ",
" ",
" $(\".logger\").append(\" Not A Win\")",
2015-08-27 22:18:09 +02:00
" return [slotOne, slotTwo, slotThree];",
2015-08-15 13:57:44 -07:00
" }",
"",
" $(document).ready(function() {",
" $(\".go\").click(function() {",
2015-08-15 13:57:44 -07:00
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = \"container inset\">",
" <div class = \"header inset\">",
" <img src=\"https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz\" alt=\"learn to code javascript at Free Code Camp logo\" class=\"img-responsive nav-logo\">",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = \"slots inset\">",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = \"outset\">",
" <button class = \"go inset\">",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = \"foot inset\">",
" <span class = \"logger\"></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"type": "waypoint",
"challengeType": 0,
"nameEs": "Crea una máquina tragamonedas en JavaScript",
"descriptionEs": [
"Ahora vamos a tratar de combinar algunas de las cosas que hemos aprendido para crear la lógica de una máquina tragamonedas.",
"Para esto tendremos que generar tres números aleatorios entre <code>1</code> y <code>3</code> que representen los valores posibles de cada casilla.",
"Guarda los tres números aleatorios en <code>slotOne</code>, <code>slotTwo</code> y <code>slotThree</code>.",
"Genera los números aleatorios utilizando el sistema que usamos anteriormente (puedes encontrar una explicación de la fórmula <a href=\"https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Waypoint-Generate-Random-Whole-Numbers-within-a-Range#explanation\">aquí</a>):",
"<code>Math.floor(Math.random() * (3 - 1 + 1)) + 1;</code>"
]
2015-08-15 13:57:44 -07:00
},
{
"id": "cf1111c1c13feddfaeb1bdef",
2015-08-15 13:57:44 -07:00
"title": "Add your JavaScript Slot Machine Slots",
2015-11-18 12:03:22 -08:00
"isBeta": true,
"description": [
2015-08-16 04:05:15 -07:00
"Now that our slots will each generate random numbers, we need to check whether they've all returned the same number.",
2015-11-09 11:56:14 +05:30
"If they have, we should notify our user that they've won and we should return <code>null</code>.",
"<code>null</code> is a JavaScript data structure that means nothing.",
"The user wins when all the three numbers match. Let's create an <code>if statement</code> with multiple conditions in order to check whether all numbers are equal.",
"<code>if(slotOne === slotTwo && slotTwo === slotThree){</code>",
"<code>&nbsp;&nbsp;return null;</code>",
2015-11-09 11:56:14 +05:30
"<code>}</code>",
"Also, we need to show the user that he has won the game when he gets the same number in all the slots.",
2015-11-13 10:19:39 +05:30
"If all three numbers match, we should also set the text <code>\"It's A Win\"</code> to the element with class <code>logger</code>."
2015-08-15 13:57:44 -07:00
],
"tests": [
"assert((function(){var data = runSlots();return data === null || data.toString().length === 1;})(), 'message: If all three of our random numbers are the same we should return that number. Otherwise we should return <code>null</code>.');"
2015-08-15 13:57:44 -07:00
],
"challengeSeed": [
2015-08-15 13:57:44 -07:00
"fccss",
" function runSlots() {",
2015-08-15 13:57:44 -07:00
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
2015-08-16 04:05:15 -07:00
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
2015-08-15 13:57:44 -07:00
" ",
2015-08-16 04:05:15 -07:00
" slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
2015-08-15 13:57:44 -07:00
" ",
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
2015-11-09 11:56:14 +05:30
" if(slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined){",
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
2015-08-15 13:57:44 -07:00
" }",
2015-11-09 11:56:14 +05:30
" ",
" $(\".logger\").append(\" Not A Win\");",
" ",
2015-08-27 22:18:09 +02:00
" return [slotOne, slotTwo, slotThree];",
2015-08-15 13:57:44 -07:00
" }",
"",
" $(document).ready(function() {",
" $(\".go\").click(function() {",
2015-08-15 13:57:44 -07:00
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = \"container inset\">",
" <div class = \"header inset\">",
" <img src=\"https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz\" alt=\"learn to code javascript at Free Code Camp logo\" class=\"img-responsive nav-logo\">",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = \"slots inset\">",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = \"outset\">",
" <button class = \"go inset\">",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = \"foot inset\">",
" <span class = \"logger\"></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"type": "waypoint",
"challengeType": 0,
"nameEs": "Añade casillas a tu tragamonedas JavaScript",
"descriptionEs": [
"Ahora que cada una de nuestras casillas genera números aleatorios, tenemos que comprobar si todos quedan con el mismo número.",
"Si es así, debemos notificar a nuestros usuarios que han ganado y debemos retornar <code>null</code>.",
"<code>null</code> es una estructura de datos de JavaScript que significa \"nada\".",
"El usuario gana cuando los tres números coinciden. Cremos una instrucción <code>if</code> con varias condiciones, a fin de comprobar si todos los números son iguales. ",
"<code>if(slotOne === slotTwo && slotTwo === slotThree){</code>",
"<code>&nbsp;&nbsp;return null;</code>",
"<code>}</code>",
"Además, tenemos que mostrar al usuario que ha ganado la partida e caso de que esté el mismo número en todas las casillas.",
"Si los tres números coinciden, también hay que poner el texto <code>\"It's A Win\"</code> en el elemento HTML con clase <code>logger</code>."
]
2015-08-15 13:57:44 -07:00
},
{
"id": "cf1111c1c13feddfaeb2bdef",
2015-08-15 13:57:44 -07:00
"title": "Bring your JavaScript Slot Machine to Life",
2015-11-18 12:03:22 -08:00
"isBeta": true,
"description": [
2015-08-15 13:57:44 -07:00
"Now we can detect a win. Let's get this slot machine working.",
2015-08-16 04:05:15 -07:00
"Let's use the jQuery <code>selector</code> <code>$(\".slot\")</code> to select all of the slots.",
"Once they are all selected, we can use <code>bracket notation</code> to access each individual slot:",
"<code>$($(\".slot\")[0]).html(slotOne);</code>",
2015-11-09 11:56:14 +05:30
"This jQuery will select the first slot and update it's HTML to display the correct number.",
2015-08-16 04:05:15 -07:00
"Use the above selector to display each number in its corresponding slot."
2015-08-15 13:57:44 -07:00
],
"tests": [
"assert((function(){runSlots();if($($(\".slot\")[0]).html().replace(/\\s/gi, \"\") !== \"\" && $($(\".slot\")[1]).html().replace(/\\s/gi, \"\") !== \"\" && $($(\".slot\")[2]).html().replace(/\\s/gi, \"\") !== \"\"){return true;}else{return false;}})(), 'message: You should be displaying the result of the slot numbers in the corresponding slots.');",
"assert((code.match( /\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)/gi) && code.match( /\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)/gi ).length >= 3 && code.match( /\\.html\\(slotOne\\)/gi ) && code.match( /\\.html\\(slotTwo\\)/gi ) && code.match( /\\.html\\(slotThree\\)/gi )), 'message: You should have used the the selector given in the description to select each slot and assign it the value of <code>slotOne</code>&#44; <code>slotTwo</code> and <code>slotThree</code> respectively.');"
2015-08-15 13:57:44 -07:00
],
"challengeSeed": [
2015-08-15 13:57:44 -07:00
"fccss",
" function runSlots() {",
2015-08-15 13:57:44 -07:00
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
2015-08-16 04:05:15 -07:00
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
2015-08-15 13:57:44 -07:00
" ",
2015-08-16 04:05:15 -07:00
" slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
2015-08-15 13:57:44 -07:00
" ",
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
" if (slotOne === slotTwo && slotTwo === slotThree) {",
2015-11-09 11:56:14 +05:30
" $(\".logger\").html(\" It's A Win\")",
" return null;",
2015-08-15 13:57:44 -07:00
" }",
" ",
2015-11-09 11:56:14 +05:30
" if(slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined){",
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
2015-08-15 13:57:44 -07:00
" }",
" ",
2015-11-09 11:56:14 +05:30
" $(\".logger\").append(\" Not A Win\");",
" ",
" ",
2015-08-27 22:18:09 +02:00
" return [slotOne, slotTwo, slotThree];",
2015-08-15 13:57:44 -07:00
" }",
"",
" $(document).ready(function() {",
" $(\".go\").click(function() {",
2015-08-15 13:57:44 -07:00
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = \"container inset\">",
" <div class = \"header inset\">",
" <img src=\"https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz\" alt=\"learn to code javascript at Free Code Camp logo\" class=\"img-responsive nav-logo\">",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = \"slots inset\">",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = \"outset\">",
" <button class = \"go inset\">",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = \"foot inset\">",
" <span class = \"logger\"></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" text-align: center;",
" padding-top: 25px;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"type": "waypoint",
"challengeType": 0,
"nameEs": "Da vida a tu máquina tragamonedas en JavaScript",
"descriptionEs": [
"Ahora podemos detectar una victoria. Logremos que la máquina tragamonedas funcione. ",
"Usemos un <code>selector</code> de jQuery <code>$(\".slot\")</code> para seleccionar todas las casillas.",
"Una vez que todas estén seleccionados, podemos usar <code>notación de corchetes</code> para acceder a cada casilla individual:",
"<code>$($(\".slot\")[0]).html(slotOne);</code>",
"Este jQuery seleccionará la primera ranura y actualizará su HTML para mostrar el número correcto.",
"Usa el selector anterior para mostrar cada número en su casilla correspondiente."
]
2015-08-15 13:57:44 -07:00
},
{
"id": "cf1111c1c11feddfaeb1bdff",
"title": "Give your JavaScript Slot Machine some Stylish Images",
2015-11-18 12:03:22 -08:00
"isBeta": true,
"description": [
2015-08-16 04:05:15 -07:00
"Now let's add some images to our slots.",
"We've already set up the images for you in an array called <code>images</code>. We can use different indexes to grab each of these.",
"Here's how we would set the first slot to show a different image depending on which number its random number generates:",
"<code>$($('.slot')[0]).html('&lt;img src = \"' + images[slotOne-1] + '\"&gt;');</code>",
"Set up all three slots like this, then click the \"Go\" button to play the slot machine."
2015-08-15 13:57:44 -07:00
],
"tests": [
"assert((code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\s*?\\'\\<img\\s?src\\s?=\\s?\"\\'\\s?\\+\\s?images\\[\\w+\\s*\\-\\s*1\\]\\s?\\+\\s?\\'\"\\>\\'\\s*?\\);/gi) && code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\s*?\\'\\<img\\s?src\\s?=\\s?\"\\'\\s?\\+\\s?images\\[\\w+\\s*\\-\\s*1\\]\\s?\\+\\s?\\'\"\\>\\'\\s*?\\);/gi).length >= 3), 'message: Use the provided code three times. One for each slot.');",
"assert(code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[0\\]\\s*?\\)/gi), 'message: You should have used <code>$&#40;&#39;.slot&#39;&#41;[0]</code> at least once.');",
"assert(code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[1\\]\\s*?\\)/gi), 'message: You should have used <code>$&#40;&#39;.slot&#39;&#41;[1]</code> at least once.');",
"assert(code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[2\\]\\s*?\\)/gi), 'message: You should have used <code>$&#40;&#39;.slot&#39;&#41;[2]</code> at least once.');",
"assert(code.match(/slotOne/gi) && code.match(/slotOne/gi).length >= 7, 'message: You should have used the <code>slotOne</code> value at least once.');",
"assert(code.match(/slotTwo/gi) && code.match(/slotTwo/gi).length >= 8, 'message: You should have used the <code>slotTwo</code> value at least once.');",
"assert(code.match(/slotThree/gi) && code.match(/slotThree/gi).length >= 7, 'message: You should have used the <code>slotThree</code> value at least once.');"
2015-08-15 13:57:44 -07:00
],
"challengeSeed": [
2015-08-15 13:57:44 -07:00
"fccss",
" function runSlots() {",
2015-08-15 13:57:44 -07:00
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
2015-08-16 04:05:15 -07:00
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
2015-08-15 13:57:44 -07:00
" ",
2015-08-16 04:05:15 -07:00
" slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
2015-08-15 13:57:44 -07:00
" ",
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
" if (slotOne === slotTwo && slotTwo === slotThree) {",
2015-11-09 11:56:14 +05:30
" $('.logger').html(\"It's A Win\");",
" return null;",
2015-08-15 13:57:44 -07:00
" }",
" ",
2015-11-09 11:56:14 +05:30
" if(slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined){",
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
2015-08-15 13:57:44 -07:00
" }",
" ",
2015-11-09 11:56:14 +05:30
" $('.logger').append(\" Not A Win\");",
" ",
2015-08-27 22:18:09 +02:00
" return [slotOne, slotTwo, slotThree];",
2015-08-15 13:57:44 -07:00
" }",
"",
" $(document).ready(function() {",
" $('.go').click(function() {",
2015-08-15 13:57:44 -07:00
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = 'container inset'>",
" <div class = 'header inset'>",
" <img src='https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz' alt='learn to code javascript at Free Code Camp logo' class='img-responsive nav-logo'>",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = 'slots inset'>",
" <div class = 'slot inset'>",
" ",
" </div>",
" <div class = 'slot inset'>",
" ",
" </div>",
" <div class = 'slot inset'>",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = 'outset'>",
" <button class = 'go inset'>",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = 'foot inset'>",
" <span class = 'logger'></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .slot > img {",
" margin: 0!important;",
" height: 71px;",
" width: 50px;",
" }",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" width: 50px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" text-align: center;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"type": "waypoint",
"challengeType": 0,
"nameEs": "Dale a tu máquina tragamonedas JavaScript algunas imágenes con estilo",
"descriptionEs": [
"Ahora añadamos algunas imágenes en nuestras casillas.",
"Ya hemos creado las imágenes por ti en una matriz llamada <code>images</code>. Podemos utilizar diferentes índices para tomara cada una de estas. ",
"Aquí está como haríamos que la primera casilla muestre una imagen diferente dependiendo del número aleatorio que se genere:",
"<code>$($('.slot')[0]).html('&lt;img src = \"' + images[slotOne-1] + '\"&gt;');</code>",
"Configura las tres casillas de manera análoga, a continuación, pulsa el botón \"Go\" para jugar con la máquina tragamonedas."
]
2015-07-05 17:12:52 -07:00
}
]
}