From 792e6579816a3ec1f88cb738de8bfb3394d36e36 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Sun, 29 Sep 2019 06:55:26 -0300 Subject: [PATCH 1/5] 1-5-1 --- .../01-primitives-methods/article.md | 98 +++++++++---------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index a2dcceb19..414297f3a 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -1,22 +1,22 @@ -# Methods of primitives +# Métodos de primitivos -JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects. +JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos. -They also provide methods to call as such. We will study those soon, but first we'll see how it works because, of course, primitives are not objects (and here we will make it even clearer). +También proveen, como aquellos, métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente). -Let's look at the key distinctions between primitives and objects. +Veamos las diferencias clave entre primitivos y objetos. -A primitive +Un primitivo -- Is a value of a primitive type. -- There are 6 primitive types: `string`, `number`, `boolean`, `symbol`, `null` and `undefined`. +- Es un valor de tipo primitivo. +- Hay 6 tipos primitivos: `string`, `number`, `boolean`, `symbol`, `null` y `undefined`. -An object +Un objeto -- Is capable of storing multiple values as properties. -- Can be created with `{}`, for instance: `{name: "John", age: 30}`. There are other kinds of objects in JavaScript; functions, for example, are objects. +- Es capaz de almacenar múltiples valores como propiedades. +- Puede ser creado con `{}`, por ejemplo: `{name: "John", age: 30}`. Hay otras clases de objetos en JavaScript; por ejemplo, las funciones (`function`) son objetos . -One of the best things about objects is that we can store a function as one of its properties. +Una de las mejores cosas de los objetos es que podemos almacenar una función como una de sus propiedades. ```js run let john = { @@ -29,32 +29,32 @@ let john = { john.sayHi(); // Hi buddy! ``` -So here we've made an object `john` with the method `sayHi`. +Aquí hemos hecho un función `john` con el método `sayHi` (saludar). -Many built-in objects already exist, such as those that work with dates, errors, HTML elements, etc. They have different properties and methods. +Ya existen muchos objetos incorporados, como aquellos que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos. -But, these features come with a cost! +¡Pero estas características vienen con un costo! -Objects are "heavier" than primitives. They require additional resources to support the internal machinery. But as properties and methods are very useful in programming, JavaScript engines try to optimize them to reduce the additional burden. +Los objetos son más "pesados" que los primitivos. Requieren recursos adicionales para soportar su maquinaria interna. Pero como las propiedades y los métodos son tan útiles en programación, los motores JavaScript tratan de optimizarlos para reducir su carga adiional. -## A primitive as an object +## Un primitivo como objeto -Here's the paradox faced by the creator of JavaScript: +Aquí la paradoja que enfrentó el creador de JavaScript: -- There are many things one would want to do with a primitive like a string or a number. It would be great to access them as methods. -- Primitives must be as fast and lightweight as possible. +- Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso acceder a métodos. +- Los Primitivos deben ser tan rápidos y livianos como sea posible. -The solution looks a little bit awkward, but here it is: +La solución se ve algo enrevesada, pero aquí está: -1. Primitives are still primitive. A single value, as desired. -2. The language allows access to methods and properties of strings, numbers, booleans and symbols. -3. When this happens, a special "object wrapper" that provides the extra functionality is created, and then is destroyed. +1. Los primitivos son aún primitivos. Con un valor único, como es deseable. +2. El lenguaje permite acceder a métodos y propiedades de strings, numbers, booleans y symbols. +3. Cuando esto ocurre, un "object wrapper" (objeto envoltura) especial que provee la funcionalidad extra es creado y luego destruido. -The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean` and `Symbol`. Thus, they provide different sets of methods. +Los "object wrappers" son diferentes para cada tipo primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así proveen diferentes sets de métodos. -For instance, there exists a method [str.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) that returns a capitalized string. +Por ejemplo, hay un método [str.toUpperCase()](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/toUpperCase) que devuelve un string en mayúsculas. -Here's how it works: +Aquí cómo funciona: ```js run let str = "Hello"; @@ -62,17 +62,17 @@ let str = "Hello"; alert( str.toUpperCase() ); // HELLO ``` -Simple, right? Here's what actually happens in `str.toUpperCase()`: +Simple, ¿no es así? Lo que realmente ocurre en `str.toUpperCase()`: -1. The string `str` is a primitive. So in the moment of accessing its property, a special object is created that knows the value of the string, and has useful methods, like `toUpperCase()`. -2. That method runs and returns a new string (shown by `alert`). -3. The special object is destroyed, leaving the primitive `str` alone. +1. El string `str` es un tipo primitivo. Entonces al momento de acceder a su propiedad, un objeto especial es creado, uno que conoce el valor del string y tiene métodos útiles como `toUpperCase()`. +2. El método se ejecuta y devuelve un nuevo string (el mostrado con `alert`). +3. El objeto especial es destruido, dejando solo el primitivo `str`. -So primitives can provide methods, but they still remain lightweight. +Así las primitivas pueden proveer métodos y aún permanecer livianas. -The JavaScript engine highly optimizes this process. It may even skip the creation of the extra object at all. But it must still adhere to the specification and behave as if it creates one. +El motor JavaScript optimiza este proceso enormemente. Puede incluso saltear la creación del objeto extra por completo. Pero aún debe adherir a la especificación y comportarse como si creara uno. -A number has methods of its own, for instance, [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) rounds the number to the given precision: +Un number tiene sus propios métodos, por ejemplo [toFixed(n)](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Number/toFixed) redondea el número a la precisión dada: ```js run let n = 1.23456; @@ -80,15 +80,15 @@ let n = 1.23456; alert( n.toFixed(2) ); // 1.23 ``` -We'll see more specific methods in chapters and . +Veremos más métodos específicos en los capítulos y . -````warn header="Constructors `String/Number/Boolean` are for internal use only" -Some languages like Java allow us to create "wrapper objects" for primitives explicitly using a syntax like `new Number(1)` or `new Boolean(false)`. +````warn header="Constructors `String/Number/Boolean` son de uso interno solamente" +Algunos lenguajes como JAva permiten crear "wrapper objects" para primitivas explícitamente usando una sintaxis como `new Number(1)` o `new Boolean(false)`. -In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places. +En JavaScript, eso también es posible por razones históricas, pero firmemente **no recomendado**. Las cosas enloquecerán en varios lugares. -For instance: +Por ejemplo: ```js run alert( typeof 1 ); // "number" @@ -96,35 +96,35 @@ alert( typeof 1 ); // "number" alert( typeof new Number(1) ); // "object"! ``` -And because what follows, `zero`, is an object, the alert will show up: +Los objetos son siempre verdaderos en un if, por ello el alert se mostrará: ```js run let zero = new Number(0); -if (zero) { // zero is true, because it's an object - alert( "zero is truthy?!?" ); +if (zero) { // zero es true, porque es un objeto + alert( "zero es verdadero?!?" ); } ``` -On the other hand, using the same functions `String/Number/Boolean` without `new` is a totally sane and useful thing. They convert a value to the corresponding type: to a string, a number, or a boolean (primitive). +Por otro lado, usar las mismas funciones `String/Number/Boolean` sin `new` es totalmente sano y útil. Ellos convierten un valor al tipo correspondiente: a un string, number, o boolean (primitivo). -For example, this is entirely valid: +Por ejemplo, esto es perfectamente válido: ```js -let num = Number("123"); // convert a string to number +let num = Number("123"); // convierte string a number ``` ```` ````warn header="null/undefined have no methods" -The special primitives `null` and `undefined` are exceptions. They have no corresponding "wrapper objects" and provide no methods. In a sense, they are "the most primitive". +Las primitivas especiales `null` y `undefined` son excepciones. No tienen "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo". -An attempt to access a property of such value would give the error: +El intento de acceder a una propiedad de tal valor daría error: ```js run alert(null.test); // error ```` -## Summary +## Resumen -- Primitives except `null` and `undefined` provide many helpful methods. We will study those in the upcoming chapters. -- Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call. +- Las primitivas excepto `null` y `undefined` proveen muchos métodos útiles. Los estudiaremos en los próximos capítulos. +- Formalmente, estos métodos trabajan a través de objetos temporales, pero los motores de JavaScript están bien afinados para optimizarlos internamente, así que llamarlos no es costoso. From ba637d153d70a3b442750dfd172e26abc432aa8d Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Sun, 29 Sep 2019 09:00:55 -0300 Subject: [PATCH 2/5] 1.5.1 +task+sol --- .../1-string-new-property/solution.md | 24 +++++++++---------- .../1-string-new-property/task.md | 6 ++--- .../01-primitives-methods/article.md | 10 ++++---- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index a169f7769..24a6f028a 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -1,5 +1,5 @@ -Try running it: +Prueba a ejecutar: ```js run let str = "Hello"; @@ -9,23 +9,23 @@ str.test = 5; // (*) alert(str.test); ``` -There may be two kinds of result: +Puede haber dos clases de resultado: 1. `undefined` -2. An error. +2. Un error. -Why? Let's replay what's happening at line `(*)`: +¿Por qué? Repasemos qué ocurre en la línea `(*)`: -1. When a property of `str` is accessed, a "wrapper object" is created. -2. The operation with the property is carried out on it. So, the object gets the `test` property. -3. The operation finishes and the "wrapper object" disappears. +1. Cuando una propiedad de `str` es accedida, un "wrapper object" es creado. +2. La operación con la propiedad es llevada a cabo con él. Entonces, el objeto obtiene la propiedad `test`. +3. La operación termina y el "wrapper object" desaparece. -So, on the last line, `str` has no trace of the property. A new wrapper object for every object operation on a string. +Entonces, en la última línea, `str` no tiene rastros de la propiedad. Por cada operación de objeto en un string, un nuevo wrapper object es usado. -Some browsers though may decide to further limit the programmer and disallow to assign properties to primitives at all. That's why in practice we can also see errors at line `(*)`. It's a little bit farther from the specification though. +Aunque algunos navegadores pueden decidir ir más allá y limitar al programador e impedir la asignación de propiedades a primitivas del todo. Por eso en la práctica podemos ver errores en la línea `(*)`. Aunque con ello van un poco más lejos que la especificación. -**This example clearly shows that primitives are not objects.** +**Este ejemlplo claramente muestra que las primitivas no son objetos.** -They just can not store data. +Ellas simplemente no pueden almacenar datos. -All property/method operations are performed with the help of temporary objects. +Todas las operaciones de propiedades y métodos son hechas con la ayuda de objetos temporales. diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md index 50c781ea5..67c764b50 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md @@ -2,10 +2,10 @@ importance: 5 --- -# Can I add a string property? +# ¿Puedo agregar un propiedad a un string? -Consider the following code: +Considera el siguiente código: ```js let str = "Hello"; @@ -15,4 +15,4 @@ str.test = 5; alert(str.test); ``` -How do you think, will it work? What will be shown? +Qué piensas, ¿funcionará? ¿Qué mostrará? diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index 414297f3a..c84f02186 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -1,8 +1,8 @@ -# Métodos de primitivos +# Métodos en datos primitivos JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos. -También proveen, como aquellos, métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente). +También proveen, como estos, métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente). Veamos las diferencias clave entre primitivos y objetos. @@ -44,7 +44,7 @@ Aquí la paradoja que enfrentó el creador de JavaScript: - Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso acceder a métodos. - Los Primitivos deben ser tan rápidos y livianos como sea posible. -La solución se ve algo enrevesada, pero aquí está: +La solución es algo enrevesada, pero aquí está: 1. Los primitivos son aún primitivos. Con un valor único, como es deseable. 2. El lenguaje permite acceder a métodos y propiedades de strings, numbers, booleans y symbols. @@ -115,8 +115,8 @@ let num = Number("123"); // convierte string a number ```` -````warn header="null/undefined have no methods" -Las primitivas especiales `null` y `undefined` son excepciones. No tienen "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo". +````warn header="null/undefined no tienen métodos" +Las primitivas especiales `null` y `undefined` son excepciones. No tienen los "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo". El intento de acceder a una propiedad de tal valor daría error: From f7dd927c6cfaab2772e5b164cac375f4b91dabe2 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Wed, 2 Oct 2019 05:44:59 -0300 Subject: [PATCH 3/5] Fixes bsed on EN version --- .../1-string-new-property/solution.md | 23 ++++------- .../1-string-new-property/task.md | 2 +- .../01-primitives-methods/article.md | 40 +++++++++---------- 3 files changed, 28 insertions(+), 37 deletions(-) diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index 24a6f028a..25ac541d9 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -9,23 +9,16 @@ str.test = 5; // (*) alert(str.test); ``` -Puede haber dos clases de resultado: -1. `undefined` -2. Un error. +Dependiendo del uso o no del modo estricto "use strict", el resultado puede ser: +1. `undefined` (sin strict mode) +2. Un error (strict mode) ¿Por qué? Repasemos qué ocurre en la línea `(*)`: -1. Cuando una propiedad de `str` es accedida, un "wrapper object" es creado. -2. La operación con la propiedad es llevada a cabo con él. Entonces, el objeto obtiene la propiedad `test`. -3. La operación termina y el "wrapper object" desaparece. +1. Cuando se accede a una propiedad de `str`, un "wrapper object" es creado. +2. Con modo estricto, alterarlo produce error. +3. De otra manera, la operación es llevada a cabo y el objeto obtiene la propiedad `test`, pero después de ello el "wrapper object" desaparece, entonces en la última linea `str` queda sin rastros de la propiedad. -Entonces, en la última línea, `str` no tiene rastros de la propiedad. Por cada operación de objeto en un string, un nuevo wrapper object es usado. - -Aunque algunos navegadores pueden decidir ir más allá y limitar al programador e impedir la asignación de propiedades a primitivas del todo. Por eso en la práctica podemos ver errores en la línea `(*)`. Aunque con ello van un poco más lejos que la especificación. - -**Este ejemlplo claramente muestra que las primitivas no son objetos.** - -Ellas simplemente no pueden almacenar datos. - -Todas las operaciones de propiedades y métodos son hechas con la ayuda de objetos temporales. +**Este ejemlplo claramente muestra que los tipos primitivos no son objetos.** +Ellos no pueden almacenar datos adicionales. diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md index 67c764b50..9fdb6735a 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md @@ -10,7 +10,7 @@ Considera el siguiente código: ```js let str = "Hello"; -str.test = 5; +str.test = 5; alert(str.test); ``` diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index c84f02186..fa243e4a3 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -1,10 +1,8 @@ # Métodos en datos primitivos -JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos. +JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos. Ellos también proveen métodos para ser llamados como tales. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente). -También proveen, como estos, métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente). - -Veamos las diferencias clave entre primitivos y objetos. +Veamos las principales diferencias entre primitivos y objetos. Un primitivo @@ -14,7 +12,7 @@ Un primitivo Un objeto - Es capaz de almacenar múltiples valores como propiedades. -- Puede ser creado con `{}`, por ejemplo: `{name: "John", age: 30}`. Hay otras clases de objetos en JavaScript; por ejemplo, las funciones (`function`) son objetos . +- Puede ser creado con `{}`, por ejemplo: `{name: "John", age: 30}`. Hay otros tipos de objetos en JavaScript; por ejemplo, las funciones son objetos. Una de las mejores cosas de los objetos es que podemos almacenar una función como una de sus propiedades. @@ -29,28 +27,28 @@ let john = { john.sayHi(); // Hi buddy! ``` -Aquí hemos hecho un función `john` con el método `sayHi` (saludar). +Aquí hemos hecho un función `john` con el método `sayHi`(saludar). Ya existen muchos objetos incorporados, como aquellos que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos. ¡Pero estas características vienen con un costo! -Los objetos son más "pesados" que los primitivos. Requieren recursos adicionales para soportar su maquinaria interna. Pero como las propiedades y los métodos son tan útiles en programación, los motores JavaScript tratan de optimizarlos para reducir su carga adiional. +Los objetos son más "pesados" que los tipos primitivos. Requieren recursos adicionales para soportar su maquinaria interna. ## Un primitivo como objeto Aquí la paradoja que enfrentó el creador de JavaScript: -- Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso acceder a métodos. +- Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso accederlas como métodos. - Los Primitivos deben ser tan rápidos y livianos como sea posible. La solución es algo enrevesada, pero aquí está: -1. Los primitivos son aún primitivos. Con un valor único, como es deseable. +1. Los primitivos siguen siendo primitivos. Con un valor único, como es deseable. 2. El lenguaje permite acceder a métodos y propiedades de strings, numbers, booleans y symbols. -3. Cuando esto ocurre, un "object wrapper" (objeto envoltura) especial que provee la funcionalidad extra es creado y luego destruido. +3. Para que esto funcione, un "object wrapper" (objeto envoltura) especial que provee la funcionalidad extra es creado, y luego destruido. -Los "object wrappers" son diferentes para cada tipo primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así proveen diferentes sets de métodos. +Los "object wrappers" son diferentes para cada tipo primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así, proveen diferentes sets de métodos. Por ejemplo, hay un método [str.toUpperCase()](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/toUpperCase) que devuelve un string en mayúsculas. @@ -68,7 +66,7 @@ Simple, ¿no es así? Lo que realmente ocurre en `str.toUpperCase()`: 2. El método se ejecuta y devuelve un nuevo string (el mostrado con `alert`). 3. El objeto especial es destruido, dejando solo el primitivo `str`. -Así las primitivas pueden proveer métodos y aún permanecer livianas. +Así las primitivas pueden proporcionar métodos y aún permanecer livianas. El motor JavaScript optimiza este proceso enormemente. Puede incluso saltear la creación del objeto extra por completo. Pero aún debe adherir a la especificación y comportarse como si creara uno. @@ -83,10 +81,10 @@ alert( n.toFixed(2) ); // 1.23 Veremos más métodos específicos en los capítulos y . -````warn header="Constructors `String/Number/Boolean` son de uso interno solamente" -Algunos lenguajes como JAva permiten crear "wrapper objects" para primitivas explícitamente usando una sintaxis como `new Number(1)` o `new Boolean(false)`. +````warn header="Los class constructor `String/Number/Boolean` son de uso interno solamente" +Algunos lenguajes como Java nos permiten crear explícitamente "wrapper objects" para primitivas usando una sintaxis como `new Number(1)` o `new Boolean(false)`. -En JavaScript, eso también es posible por razones históricas, pero firmemente **no recomendado**. Las cosas enloquecerán en varios lugares. +En JavaScript, eso también es posible por razones históricas, pero firmemente **desaconsejado**. Las cosas enloquecerán en varios lugares. Por ejemplo: @@ -96,17 +94,17 @@ alert( typeof 1 ); // "number" alert( typeof new Number(1) ); // "object"! ``` -Los objetos son siempre verdaderos en un if, por ello el alert se mostrará: +Los objetos son siempre verdaderos en un `if`, por ello el alert se mostrará: ```js run let zero = new Number(0); if (zero) { // zero es true, porque es un objeto - alert( "zero es verdadero?!?" ); + alert( "¡zero es verdadero!?" ); } ``` -Por otro lado, usar las mismas funciones `String/Number/Boolean` sin `new` es totalmente sano y útil. Ellos convierten un valor al tipo correspondiente: a un string, number, o boolean (primitivo). +Por otro lado, usar las mismas funciones `String/Number/Boolean` sin `new` es totalmente sano y útil. Ellos convierten un valor al tipo correspondiente: a un string, un number o un boolean (primitivos). Por ejemplo, esto es perfectamente válido: ```js @@ -116,7 +114,7 @@ let num = Number("123"); // convierte string a number ````warn header="null/undefined no tienen métodos" -Las primitivas especiales `null` y `undefined` son excepciones. No tienen los "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo". +Las primitivas especiales `null` y `undefined` son excepciones. No tienen los "wrapper objects" correspondientes y no proporcionan métodos. En ese sentido son "lo más primitivo". El intento de acceder a una propiedad de tal valor daría error: @@ -126,5 +124,5 @@ alert(null.test); // error ## Resumen -- Las primitivas excepto `null` y `undefined` proveen muchos métodos útiles. Los estudiaremos en los próximos capítulos. -- Formalmente, estos métodos trabajan a través de objetos temporales, pero los motores de JavaScript están bien afinados para optimizarlos internamente, así que llamarlos no es costoso. +- Los tipos primitivos excepto `null` y `undefined` proporcionan muchos métodos útiles. Los estudiaremos en los próximos capítulos. +- Oficialmente, estos métodos trabajan a través de objetos temporales, pero los motores de JavaScript están bien afinados para optimizar esto internamente así que llamarlos no es costoso. From 253be4619ebc6763a35409e6b4e7201414e6bedc Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Sun, 29 Sep 2019 09:00:55 -0300 Subject: [PATCH 4/5] 1 5 1 t5 --- .../1-string-new-property/solution.md | 27 ++++------- .../1-string-new-property/task.md | 8 ++-- .../01-primitives-methods/article.md | 46 +++++++++---------- 3 files changed, 36 insertions(+), 45 deletions(-) diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index a169f7769..25ac541d9 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -1,5 +1,5 @@ -Try running it: +Prueba a ejecutar: ```js run let str = "Hello"; @@ -9,23 +9,16 @@ str.test = 5; // (*) alert(str.test); ``` -There may be two kinds of result: -1. `undefined` -2. An error. +Dependiendo del uso o no del modo estricto "use strict", el resultado puede ser: +1. `undefined` (sin strict mode) +2. Un error (strict mode) -Why? Let's replay what's happening at line `(*)`: +¿Por qué? Repasemos qué ocurre en la línea `(*)`: -1. When a property of `str` is accessed, a "wrapper object" is created. -2. The operation with the property is carried out on it. So, the object gets the `test` property. -3. The operation finishes and the "wrapper object" disappears. +1. Cuando se accede a una propiedad de `str`, un "wrapper object" es creado. +2. Con modo estricto, alterarlo produce error. +3. De otra manera, la operación es llevada a cabo y el objeto obtiene la propiedad `test`, pero después de ello el "wrapper object" desaparece, entonces en la última linea `str` queda sin rastros de la propiedad. -So, on the last line, `str` has no trace of the property. A new wrapper object for every object operation on a string. - -Some browsers though may decide to further limit the programmer and disallow to assign properties to primitives at all. That's why in practice we can also see errors at line `(*)`. It's a little bit farther from the specification though. - -**This example clearly shows that primitives are not objects.** - -They just can not store data. - -All property/method operations are performed with the help of temporary objects. +**Este ejemlplo claramente muestra que los tipos primitivos no son objetos.** +Ellos no pueden almacenar datos adicionales. diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md index 50c781ea5..9fdb6735a 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md @@ -2,17 +2,17 @@ importance: 5 --- -# Can I add a string property? +# ¿Puedo agregar un propiedad a un string? -Consider the following code: +Considera el siguiente código: ```js let str = "Hello"; -str.test = 5; +str.test = 5; alert(str.test); ``` -How do you think, will it work? What will be shown? +Qué piensas, ¿funcionará? ¿Qué mostrará? diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index 414297f3a..fa243e4a3 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -1,10 +1,8 @@ -# Métodos de primitivos +# Métodos en datos primitivos -JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos. +JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos. Ellos también proveen métodos para ser llamados como tales. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente). -También proveen, como aquellos, métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente). - -Veamos las diferencias clave entre primitivos y objetos. +Veamos las principales diferencias entre primitivos y objetos. Un primitivo @@ -14,7 +12,7 @@ Un primitivo Un objeto - Es capaz de almacenar múltiples valores como propiedades. -- Puede ser creado con `{}`, por ejemplo: `{name: "John", age: 30}`. Hay otras clases de objetos en JavaScript; por ejemplo, las funciones (`function`) son objetos . +- Puede ser creado con `{}`, por ejemplo: `{name: "John", age: 30}`. Hay otros tipos de objetos en JavaScript; por ejemplo, las funciones son objetos. Una de las mejores cosas de los objetos es que podemos almacenar una función como una de sus propiedades. @@ -29,28 +27,28 @@ let john = { john.sayHi(); // Hi buddy! ``` -Aquí hemos hecho un función `john` con el método `sayHi` (saludar). +Aquí hemos hecho un función `john` con el método `sayHi`(saludar). Ya existen muchos objetos incorporados, como aquellos que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos. ¡Pero estas características vienen con un costo! -Los objetos son más "pesados" que los primitivos. Requieren recursos adicionales para soportar su maquinaria interna. Pero como las propiedades y los métodos son tan útiles en programación, los motores JavaScript tratan de optimizarlos para reducir su carga adiional. +Los objetos son más "pesados" que los tipos primitivos. Requieren recursos adicionales para soportar su maquinaria interna. ## Un primitivo como objeto Aquí la paradoja que enfrentó el creador de JavaScript: -- Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso acceder a métodos. +- Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso accederlas como métodos. - Los Primitivos deben ser tan rápidos y livianos como sea posible. -La solución se ve algo enrevesada, pero aquí está: +La solución es algo enrevesada, pero aquí está: -1. Los primitivos son aún primitivos. Con un valor único, como es deseable. +1. Los primitivos siguen siendo primitivos. Con un valor único, como es deseable. 2. El lenguaje permite acceder a métodos y propiedades de strings, numbers, booleans y symbols. -3. Cuando esto ocurre, un "object wrapper" (objeto envoltura) especial que provee la funcionalidad extra es creado y luego destruido. +3. Para que esto funcione, un "object wrapper" (objeto envoltura) especial que provee la funcionalidad extra es creado, y luego destruido. -Los "object wrappers" son diferentes para cada tipo primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así proveen diferentes sets de métodos. +Los "object wrappers" son diferentes para cada tipo primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así, proveen diferentes sets de métodos. Por ejemplo, hay un método [str.toUpperCase()](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/toUpperCase) que devuelve un string en mayúsculas. @@ -68,7 +66,7 @@ Simple, ¿no es así? Lo que realmente ocurre en `str.toUpperCase()`: 2. El método se ejecuta y devuelve un nuevo string (el mostrado con `alert`). 3. El objeto especial es destruido, dejando solo el primitivo `str`. -Así las primitivas pueden proveer métodos y aún permanecer livianas. +Así las primitivas pueden proporcionar métodos y aún permanecer livianas. El motor JavaScript optimiza este proceso enormemente. Puede incluso saltear la creación del objeto extra por completo. Pero aún debe adherir a la especificación y comportarse como si creara uno. @@ -83,10 +81,10 @@ alert( n.toFixed(2) ); // 1.23 Veremos más métodos específicos en los capítulos y . -````warn header="Constructors `String/Number/Boolean` son de uso interno solamente" -Algunos lenguajes como JAva permiten crear "wrapper objects" para primitivas explícitamente usando una sintaxis como `new Number(1)` o `new Boolean(false)`. +````warn header="Los class constructor `String/Number/Boolean` son de uso interno solamente" +Algunos lenguajes como Java nos permiten crear explícitamente "wrapper objects" para primitivas usando una sintaxis como `new Number(1)` o `new Boolean(false)`. -En JavaScript, eso también es posible por razones históricas, pero firmemente **no recomendado**. Las cosas enloquecerán en varios lugares. +En JavaScript, eso también es posible por razones históricas, pero firmemente **desaconsejado**. Las cosas enloquecerán en varios lugares. Por ejemplo: @@ -96,17 +94,17 @@ alert( typeof 1 ); // "number" alert( typeof new Number(1) ); // "object"! ``` -Los objetos son siempre verdaderos en un if, por ello el alert se mostrará: +Los objetos son siempre verdaderos en un `if`, por ello el alert se mostrará: ```js run let zero = new Number(0); if (zero) { // zero es true, porque es un objeto - alert( "zero es verdadero?!?" ); + alert( "¡zero es verdadero!?" ); } ``` -Por otro lado, usar las mismas funciones `String/Number/Boolean` sin `new` es totalmente sano y útil. Ellos convierten un valor al tipo correspondiente: a un string, number, o boolean (primitivo). +Por otro lado, usar las mismas funciones `String/Number/Boolean` sin `new` es totalmente sano y útil. Ellos convierten un valor al tipo correspondiente: a un string, un number o un boolean (primitivos). Por ejemplo, esto es perfectamente válido: ```js @@ -115,8 +113,8 @@ let num = Number("123"); // convierte string a number ```` -````warn header="null/undefined have no methods" -Las primitivas especiales `null` y `undefined` son excepciones. No tienen "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo". +````warn header="null/undefined no tienen métodos" +Las primitivas especiales `null` y `undefined` son excepciones. No tienen los "wrapper objects" correspondientes y no proporcionan métodos. En ese sentido son "lo más primitivo". El intento de acceder a una propiedad de tal valor daría error: @@ -126,5 +124,5 @@ alert(null.test); // error ## Resumen -- Las primitivas excepto `null` y `undefined` proveen muchos métodos útiles. Los estudiaremos en los próximos capítulos. -- Formalmente, estos métodos trabajan a través de objetos temporales, pero los motores de JavaScript están bien afinados para optimizarlos internamente, así que llamarlos no es costoso. +- Los tipos primitivos excepto `null` y `undefined` proporcionan muchos métodos útiles. Los estudiaremos en los próximos capítulos. +- Oficialmente, estos métodos trabajan a través de objetos temporales, pero los motores de JavaScript están bien afinados para optimizar esto internamente así que llamarlos no es costoso. From 0242104e2b559dabfd3cb71c56641eaa48d76d5e Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Thu, 3 Oct 2019 08:27:27 -0300 Subject: [PATCH 5/5] 1-05-2 Number, +all the tasks+sol, From EN site --- .../02-number/1-sum-interface/solution.md | 8 +- .../02-number/1-sum-interface/task.md | 6 +- .../02-number/2-why-rounded-down/solution.md | 18 +- .../02-number/2-why-rounded-down/task.md | 10 +- .../3-repeat-until-number/solution.md | 6 +- .../02-number/3-repeat-until-number/task.md | 8 +- .../4-endless-loop-error/solution.md | 10 +- .../02-number/4-endless-loop-error/task.md | 4 +- .../02-number/8-random-min-max/solution.md | 10 +- .../02-number/8-random-min-max/task.md | 8 +- .../9-random-int-min-max/solution.md | 34 +- .../02-number/9-random-int-min-max/task.md | 10 +- 1-js/05-data-types/02-number/article.md | 294 +++++++++--------- 13 files changed, 213 insertions(+), 213 deletions(-) diff --git a/1-js/05-data-types/02-number/1-sum-interface/solution.md b/1-js/05-data-types/02-number/1-sum-interface/solution.md index f2c81437d..bf1689fca 100644 --- a/1-js/05-data-types/02-number/1-sum-interface/solution.md +++ b/1-js/05-data-types/02-number/1-sum-interface/solution.md @@ -1,12 +1,12 @@ ```js run demo -let a = +prompt("The first number?", ""); -let b = +prompt("The second number?", ""); +let a = +prompt("¿Primer número?", ""); +let b = +prompt("¿Segundo número?", ""); alert( a + b ); ``` -Note the unary plus `+` before `prompt`. It immediately converts the value to a number. +Observa el más unario `+` antes del `prompt`. Este de inmediato convierte el valor a número. -Otherwise, `a` and `b` would be string their sum would be their concatenation, that is: `"1" + "2" = "12"`. \ No newline at end of file +De otra manera, `a` and `b` serían string y la suma su concatenación: `"1" + "2" = "12"`. \ No newline at end of file diff --git a/1-js/05-data-types/02-number/1-sum-interface/task.md b/1-js/05-data-types/02-number/1-sum-interface/task.md index 780126640..a97f86cd2 100644 --- a/1-js/05-data-types/02-number/1-sum-interface/task.md +++ b/1-js/05-data-types/02-number/1-sum-interface/task.md @@ -2,10 +2,10 @@ importance: 5 --- -# Sum numbers from the visitor +# Suma números para el visitante -Create a script that prompts the visitor to enter two numbers and then shows their sum. +Crea un script que pida al visitante que ingrese dos números y muestra su suma. [demo] -P.S. There is a gotcha with types. +P.D. Hay una triquiñuela con los tipos. diff --git a/1-js/05-data-types/02-number/2-why-rounded-down/solution.md b/1-js/05-data-types/02-number/2-why-rounded-down/solution.md index a17a4671a..c03e5bb2a 100644 --- a/1-js/05-data-types/02-number/2-why-rounded-down/solution.md +++ b/1-js/05-data-types/02-number/2-why-rounded-down/solution.md @@ -1,33 +1,33 @@ -Internally the decimal fraction `6.35` is an endless binary. As always in such cases, it is stored with a precision loss. +Internamente la fracción decimal de `6.35` es binario sin fin. Como siempre en estos casos, es almacenado con pérdida de precisión. -Let's see: +Veamos: ```js run alert( 6.35.toFixed(20) ); // 6.34999999999999964473 ``` -The precision loss can cause both increase and decrease of a number. In this particular case the number becomes a tiny bit less, that's why it rounded down. +La pérdida de precisión puede causar que el número incremente o decremente. En este caso particular el número se vuelve ligeramente menor, por ello es redondeado hacia abajo. -And what's for `1.35`? +¿Y qué pasa con `1.35`? ```js run alert( 1.35.toFixed(20) ); // 1.35000000000000008882 ``` -Here the precision loss made the number a little bit greater, so it rounded up. +Aquí la pérdida de precisión hace el número algo mayor, por ello redondea hacia arriba. -**How can we fix the problem with `6.35` if we want it to be rounded the right way?** +**¿Cómo podemos arreglar el problema con `6.35` si queremos redondearlo de manera correcta?** -We should bring it closer to an integer prior to rounding: +Debemos llevarlo más cerca de un entero antes del redondeo: ```js run alert( (6.35 * 10).toFixed(20) ); // 63.50000000000000000000 ``` -Note that `63.5` has no precision loss at all. That's because the decimal part `0.5` is actually `1/2`. Fractions divided by powers of `2` are exactly represented in the binary system, now we can round it: +observa que `63.5` no tiene pérdida de precisión en absoluto. Esto es porque la parte decimal `0.5` es realmente `1/2`. Fracciones divididas por potencias de `2` son representadas exactamente en el sistema binario, ahora podemos redondearlo: ```js run -alert( Math.round(6.35 * 10) / 10); // 6.35 -> 63.5 -> 64(rounded) -> 6.4 +alert( Math.round(6.35 * 10) / 10); // 6.35 -> 63.5 -> 64(redondeado) -> 6.4 ``` diff --git a/1-js/05-data-types/02-number/2-why-rounded-down/task.md b/1-js/05-data-types/02-number/2-why-rounded-down/task.md index 568c26480..e17a3e69c 100644 --- a/1-js/05-data-types/02-number/2-why-rounded-down/task.md +++ b/1-js/05-data-types/02-number/2-why-rounded-down/task.md @@ -2,21 +2,21 @@ importance: 4 --- -# Why 6.35.toFixed(1) == 6.3? +# ¿Por qué 6.35.toFixed(1) == 6.3? -According to the documentation `Math.round` and `toFixed` both round to the nearest number: `0..4` lead down while `5..9` lead up. +De acuerdo a la documentación `Math.round` y `toFixed` redondean al número más cercano: `0..4` hacia abajo mientras `5..9` hacia arriba. -For instance: +Por ejemplo: ```js run alert( 1.35.toFixed(1) ); // 1.4 ``` -In the similar example below, why is `6.35` rounded to `6.3`, not `6.4`? +En el ejemplo similar que sigue, por qué `6.35` es redondeado a `6.3`, no a `6.4`? ```js run alert( 6.35.toFixed(1) ); // 6.3 ``` -How to round `6.35` the right way? +¿Como redondear `6.35` de manera correcta? diff --git a/1-js/05-data-types/02-number/3-repeat-until-number/solution.md b/1-js/05-data-types/02-number/3-repeat-until-number/solution.md index 005116d17..79cdbbb40 100644 --- a/1-js/05-data-types/02-number/3-repeat-until-number/solution.md +++ b/1-js/05-data-types/02-number/3-repeat-until-number/solution.md @@ -15,9 +15,9 @@ function readNumber() { alert(`Read: ${readNumber()}`); ``` -The solution is a little bit more intricate that it could be because we need to handle `null`/empty lines. +La solución es un poco más intrincada de lo que podría porque necesitamos manejar `null`/líneas vacías. -So we actually accept the input until it is a "regular number". Both `null` (cancel) and empty line also fit that condition, because in numeric form they are `0`. +Entonces pedimos ingresos hasta que sea un "número regular". Tanto `null` (cancel) como las líneas vacías encajan en esa condición porque un su forma numérica estos son `0`. -After we stopped, we need to treat `null` and empty line specially (return `null`), because converting them to a number would return `0`. +Una vez detenido el ingreso, necesitamos tratar especialmente los casos `null` y línea vacía (return `null`), porque convertirlos devolverían `0`. diff --git a/1-js/05-data-types/02-number/3-repeat-until-number/task.md b/1-js/05-data-types/02-number/3-repeat-until-number/task.md index 9b172fa8a..5d1f1404c 100644 --- a/1-js/05-data-types/02-number/3-repeat-until-number/task.md +++ b/1-js/05-data-types/02-number/3-repeat-until-number/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Repeat until the input is a number +# Repetir hasta que lo ingresado sea un número -Create a function `readNumber` which prompts for a number until the visitor enters a valid numeric value. +Crea una función `readNumber` que pida un número hasta que el visitante ingrese un valor numérico válido. -The resulting value must be returned as a number. +El valor resultante debe ser devuelto como número. -The visitor can also stop the process by entering an empty line or pressing "CANCEL". In that case, the function should return `null`. +El visitante puede también detener el proceso ingresando una linea vacía o presionando "CANCEL". En tal caso la funcion debe devolver `null`. [demo] diff --git a/1-js/05-data-types/02-number/4-endless-loop-error/solution.md b/1-js/05-data-types/02-number/4-endless-loop-error/solution.md index 8bc55bd02..ac662a1d7 100644 --- a/1-js/05-data-types/02-number/4-endless-loop-error/solution.md +++ b/1-js/05-data-types/02-number/4-endless-loop-error/solution.md @@ -1,6 +1,6 @@ -That's because `i` would never equal `10`. +Es porque `i` nunca será igual a `10`. -Run it to see the *real* values of `i`: +Ejecuta esto para ver los *reales* valores de `i`: ```js run let i = 0; @@ -10,8 +10,8 @@ while (i < 11) { } ``` -None of them is exactly `10`. +Ninguno de ellos es exactamente `10`. -Such things happen because of the precision losses when adding fractions like `0.2`. +Tales cosas suceden por las pérdidas de precisión cuando sumamos decimales como `0.2`. -Conclusion: evade equality checks when working with decimal fractions. \ No newline at end of file +Conclusión: evita chequeos de igualdad al trabajar con números decimales. \ No newline at end of file diff --git a/1-js/05-data-types/02-number/4-endless-loop-error/task.md b/1-js/05-data-types/02-number/4-endless-loop-error/task.md index 592ece31c..be4c64fb2 100644 --- a/1-js/05-data-types/02-number/4-endless-loop-error/task.md +++ b/1-js/05-data-types/02-number/4-endless-loop-error/task.md @@ -2,9 +2,9 @@ importance: 4 --- -# An occasional infinite loop +# Un bucle infinito ocasional -This loop is infinite. It never ends. Why? +Este bucle es infinito. Nunca termina. ¿Por qué? ```js let i = 0; diff --git a/1-js/05-data-types/02-number/8-random-min-max/solution.md b/1-js/05-data-types/02-number/8-random-min-max/solution.md index 8736c3d56..6c45beb55 100644 --- a/1-js/05-data-types/02-number/8-random-min-max/solution.md +++ b/1-js/05-data-types/02-number/8-random-min-max/solution.md @@ -1,11 +1,11 @@ -We need to "map" all values from the interval 0..1 into values from `min` to `max`. +Necesitamos hacer un "mapeo" de todos los valores del intervalo 0..1 a valores desde `min` a `max`. -That can be done in two stages: +Esto puede hacerse en dos pasos: -1. If we multiply a random number from 0..1 by `max-min`, then the interval of possible values increases `0..1` to `0..max-min`. -2. Now if we add `min`, the possible interval becomes from `min` to `max`. +1. Si multiplicamos el número aleatorio 0..1 por `max-min`, el intervalo de valores posibles `0..1` se convierte a `0..max-min`. +2. Luego sumamos `min`, entonces el intervalo posible se convierte a `min..max`. -The function: +La función: ```js run function random(min, max) { diff --git a/1-js/05-data-types/02-number/8-random-min-max/task.md b/1-js/05-data-types/02-number/8-random-min-max/task.md index 7037cfcbb..bbadde423 100644 --- a/1-js/05-data-types/02-number/8-random-min-max/task.md +++ b/1-js/05-data-types/02-number/8-random-min-max/task.md @@ -2,13 +2,13 @@ importance: 2 --- -# A random number from min to max +# Un número aleatorio entre min y max -The built-in function `Math.random()` creates a random value from `0` to `1` (not including `1`). +La función incorporada `Math.random()` crea un valor aleatorio entre `0` y `1` (no incluyendo `1`). -Write the function `random(min, max)` to generate a random floating-point number from `min` to `max` (not including `max`). +Escribe una función `random(min, max)` para generar un número de punto flotante entre `min` y `max` (no incluyendo `max`). -Examples of its work: +Ejemplos de funcionamiento: ```js alert( random(1, 5) ); // 1.2345623452 diff --git a/1-js/05-data-types/02-number/9-random-int-min-max/solution.md b/1-js/05-data-types/02-number/9-random-int-min-max/solution.md index 0950ff812..a731d2346 100644 --- a/1-js/05-data-types/02-number/9-random-int-min-max/solution.md +++ b/1-js/05-data-types/02-number/9-random-int-min-max/solution.md @@ -1,6 +1,6 @@ -# The simple but wrong solution +# La solución simple pero equivocada -The simplest, but wrong solution would be to generate a value from `min` to `max` and round it: +La solución más simple pero equivocada sería generar un valor entre `min` y `max` y redondearlo: ```js run function randomInteger(min, max) { @@ -11,23 +11,23 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ``` -The function works, but it is incorrect. The probability to get edge values `min` and `max` is two times less than any other. +La función trabaja, pero es incorrecta. La probabilidad de obtener los valores extremos `min` y `max` es la mitad de la de los demás. -If you run the example above many times, you would easily see that `2` appears the most often. +Si ejecutas el ejemplo que sigue muchas veces, fácilmente verás que `2` aparece más a menudo. -That happens because `Math.round()` gets random numbers from the interval `1..3` and rounds them as follows: +Esto ocurre porque `Math.round()` obtiene los números del intervalo `1..3` y los redondea como sigue: ```js no-beautify -values from 1 ... to 1.4999999999 become 1 -values from 1.5 ... to 2.4999999999 become 2 -values from 2.5 ... to 2.9999999999 become 3 +valores desde 1 ... hasta 1.4999999999 se convierten en 1 +valores desde 1.5 ... hasta 2.4999999999 se convierten en 2 +valores desde 2.5 ... hasta 2.9999999999 se convierten en 3 ``` -Now we can clearly see that `1` gets twice less values than `2`. And the same with `3`. +Ahora podemos ver claramente que `1` obtiene la mitad de valores que `2`. Y lo mismo con `3`. -# The correct solution +# La solución correcta -There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from `0.5 to 3.5`, thus adding the required probabilities to the edges: +Hay muchas soluciones correctas para la tarea. Una es ajustar los bordes del intervalo. Para asegurarse los mismos intervalos, podemos generar valores entre `0.5 a 3.5`, así sumando las probabilidades requeridas a los extremos: ```js run *!* @@ -41,7 +41,7 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ``` -An alternative way could be to use `Math.floor` for a random number from `min` to `max+1`: +Una alternativa es el uso de `Math.floor` para un número aleatorio entre `min` y `max+1`: ```js run *!* @@ -55,12 +55,12 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ``` -Now all intervals are mapped this way: +Ahora todos los intervalos son mapeados de esta forma: ```js no-beautify -values from 1 ... to 1.9999999999 become 1 -values from 2 ... to 2.9999999999 become 2 -values from 3 ... to 3.9999999999 become 3 +valores desde 1 ... hasta 1.9999999999 se convierten en 1 +valores desde 2 ... hasta 2.9999999999 se convierten en 2 +valores desde 3 ... hasta 3.9999999999 se convierten en 3 ``` -All intervals have the same length, making the final distribution uniform. +Todos los intervalos tienen el mismo largo, haciendo la distribución final uniforme. diff --git a/1-js/05-data-types/02-number/9-random-int-min-max/task.md b/1-js/05-data-types/02-number/9-random-int-min-max/task.md index 29341b2af..335ca0f58 100644 --- a/1-js/05-data-types/02-number/9-random-int-min-max/task.md +++ b/1-js/05-data-types/02-number/9-random-int-min-max/task.md @@ -2,14 +2,14 @@ importance: 2 --- -# A random integer from min to max +# Un entero aleatorio entre min y max -Create a function `randomInteger(min, max)` that generates a random *integer* number from `min` to `max` including both `min` and `max` as possible values. +Crea una función `randomInteger(min, max)` que genere un número *integer* aleatorio entre `min` y `max` incluyendo ambos, `min` y `max`, como valores posibles. -Any number from the interval `min..max` must appear with the same probability. +Todo número del intervalo `min..max` debe aparecer con la misma probabilidad. -Examples of its work: +Ejemplos de funcionamiento: ```js alert( random(1, 5) ); // 1 @@ -17,4 +17,4 @@ alert( random(1, 5) ); // 3 alert( random(1, 5) ); // 5 ``` -You can use the solution of the [previous task](info:task/random-min-max) as the base. +Puedes usar la solución de la [tarea previa](info:task/random-min-max) como base. diff --git a/1-js/05-data-types/02-number/article.md b/1-js/05-data-types/02-number/article.md index 7ca012c27..ccca73695 100644 --- a/1-js/05-data-types/02-number/article.md +++ b/1-js/05-data-types/02-number/article.md @@ -1,28 +1,28 @@ -# Numbers +# Números -All numbers in JavaScript are stored in 64-bit format [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985), also known as "double precision". +Todos los números en JavaScript son almacenados en formato de 64-bit [IEEE-754](https://es.wikipedia.org/wiki/IEEE_coma_flotante), también conocido como "números de double precisión de coma flotante". -Let's recap and expand upon what we currently know about them. +Extendamos lo que ya sabemos de ellos. -## More ways to write a number +## Más formas de escribir un número -Imagine we need to write 1 billion. The obvious way is: +Imagina que necesitamos escribir mil millones ("1 billion" en inglés, no confundir con "billón", millones de millones). La forma obvia es: ```js let billion = 1000000000; ``` -But in real life we usually avoid writing a long string of zeroes as it's easy to mistype. Also, we are lazy. We will usually write something like `"1bn"` for a billion or `"7.3bn"` for 7 billion 300 million. The same is true for most large numbers. +En la vida real tratamos de evitar esribir una larga cadena de ceros porque es fácil tipear mal. -In JavaScript, we shorten a number by appending the letter `"e"` to the number and specifying the zeroes count: +En JavaScript, acortamos un número agregando la letra `"e"` y especificando la cantidad de ceros: ```js run -let billion = 1e9; // 1 billion, literally: 1 and 9 zeroes +let billion = 1e9; // 1 billion, mil millones, literalmente: 1 y 9 ceros -alert( 7.3e9 ); // 7.3 billions (7,300,000,000) +alert( 7.3e9 ); // 7.3 billions (7,3 miles de millones 7300 000 000) ``` -In other words, `"e"` multiplies the number by `1` with the given zeroes count. +En otras palabras, `"e"` multiplica el número por el `1` seguido de la cantidad de ceros dada. ```js 1e3 = 1 * 1000 @@ -30,58 +30,58 @@ In other words, `"e"` multiplies the number by `1` with the given zeroes count. ``` -Now let's write something very small. Say, 1 microsecond (one millionth of a second): +Ahora escribamos algo muy pequeño. Digamos, 1 microsegundo (un millonésimo de segundo): ```js let ms = 0.000001; ``` -Just like before, using `"e"` can help. If we'd like to avoid writing the zeroes explicitly, we could say: +Como antes, el uso de `"e"` puede ayudar. Si queremos evitar la escritura de ceros explícitamente, podemos decir: ```js -let ms = 1e-6; // six zeroes to the left from 1 +let ms = 1e-6; // seis ceros a la izquierda del 1 ``` -If we count the zeroes in `0.000001`, there are 6 of them. So naturally it's `1e-6`. +Si contamos los ceros en `0.000001`, hay 6 de ellos. Entonces naturalmente es `1e-6`. -In other words, a negative number after `"e"` means a division by 1 with the given number of zeroes: +En otras palabras, un número negativo detrás de `"e"` significa una división por el 1 seguido de la cantidad dada de ceros: ```js -// -3 divides by 1 with 3 zeroes +// -3 divide por 1 con 3 ceros 1e-3 = 1 / 1000 (=0.001) -// -6 divides by 1 with 6 zeroes +// -6 divide por 1 con 6 ceros 1.23e-6 = 1.23 / 1000000 (=0.00000123) ``` -### Hex, binary and octal numbers +### Números hexadecimales, binarios y octales -[Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) numbers are widely used in JavaScript to represent colors, encode characters, and for many other things. So naturally, there exists a shorter way to write them: `0x` and then the number. +Los números [Hexadecimales](https://es.wikipedia.org/wiki/Sistema_hexadecimal) son ampliamente usados en JavaScript para representar colores, codificar caracteres y muchas otras cosas. Naturalmente existe una manera breve de escribirlos: `0x` y luego el número. -For instance: +Por ejemplo: ```js run alert( 0xff ); // 255 -alert( 0xFF ); // 255 (the same, case doesn't matter) +alert( 0xFF ); // 255 (lo mismo en mayúsculas o minúsculas ) ``` -Binary and octal numeral systems are rarely used, but also supported using the `0b` and `0o` prefixes: +Los sistemas binario y octal son raramente usados, pero también soportados mediante el uso de los prefijos `0b` and `0o`: ```js run -let a = 0b11111111; // binary form of 255 -let b = 0o377; // octal form of 255 +let a = 0b11111111; // binario de 255 +let b = 0o377; // octal de 255 -alert( a == b ); // true, the same number 255 at both sides +alert( a == b ); // true, el mismo número 255 en ambos lados ``` -There are only 3 numeral systems with such support. For other numeral systems, we should use the function `parseInt` (which we will see later in this chapter). +Hay solo 3 sistemas numéricos con tal soporte. Para otros sistemas numéricos, debemos usar la función `parseInt` (que veremos luego en este capítulo). ## toString(base) -The method `num.toString(base)` returns a string representation of `num` in the numeral system with the given `base`. +El método `num.toString(base)` devuelve la representación `num` en una cadena, en el sistema numérico con la `base` dada. -For example: +Ejemplo: ```js run let num = 255; @@ -89,45 +89,45 @@ alert( num.toString(16) ); // ff alert( num.toString(2) ); // 11111111 ``` -The `base` can vary from `2` to `36`. By default it's `10`. +La `base` puede variar entre `2` y `36`. La predeterminada es `10`. -Common use cases for this are: +Casos de uso comunes son: -- **base=16** is used for hex colors, character encodings etc, digits can be `0..9` or `A..F`. -- **base=2** is mostly for debugging bitwise operations, digits can be `0` or `1`. -- **base=36** is the maximum, digits can be `0..9` or `A..Z`. The whole latin alphabet is used to represent a number. A funny, but useful case for `36` is when we need to turn a long numeric identifier into something shorter, for example to make a short url. Can simply represent it in the numeral system with base `36`: +- **base=16** usada para colores hex, codificación de caracteres, etc; los dígitos pueden ser `0..9` o `A..F`. +- **base=2** mayormente usada para el debug de operaciones de bit, los dígitos pueden ser `0` o `1`. +- **base=36** Es el máximo, los dígitos pueden ser `0..9` o `A..Z`. El alfabeto completo es usado para representar un número. Un peculiar pero práctico uso para `36` es cuando necesitamos convertir un largo identificador numérico en algo más corto, por ejemplo para abreviar una url. Podemos simplemente representarlo en el sistema numeral de base `36`: ```js run alert( 123456..toString(36) ); // 2n9c ``` -```warn header="Two dots to call a method" -Please note that two dots in `123456..toString(36)` is not a typo. If we want to call a method directly on a number, like `toString` in the example above, then we need to place two dots `..` after it. +```warn header="Dos puntos para llamar un método" +Por favor observa que los dos puntos en `123456..toString(36)` no son un error tipográfico. Si queremos llamar un método directamente sobre el número, como `toString` del ejemplo anterior, necesitamos ubicar los dos puntos `..` tras él. -If we placed a single dot: `123456.toString(36)`, then there would be an error, because JavaScript syntax implies the decimal part after the first dot. And if we place one more dot, then JavaScript knows that the decimal part is empty and now goes the method. +Si pusiéramos un único punto: `123456.toString(36)`, habría un error, porque la sintaxis de JavaScript implica una parte decimal después del primer punto. Al poner un punto más, JavaScript reconoce que la parte decimal está vacía y luego va el método. -Also could write `(123456).toString(36)`. +También podríamos escribir `(123456).toString(36)`. ``` -## Rounding +## Redondeo -One of the most used operations when working with numbers is rounding. +Una de las operaciones más usadas cuando se trabaja con números es el redondeo. -There are several built-in functions for rounding: +Hay varias funciones incorporadas para el redondeo: `Math.floor` -: Rounds down: `3.1` becomes `3`, and `-1.1` becomes `-2`. +: Redondea hacia abajo: `3.1` torna en `3`, y `-1.1` torna en `-2`. `Math.ceil` -: Rounds up: `3.1` becomes `4`, and `-1.1` becomes `-1`. +: Redondea hacia arriba: `3.1` torna en `4`, y `-1.1` torna en `-1`. `Math.round` -: Rounds to the nearest integer: `3.1` becomes `3`, `3.6` becomes `4` and `-1.1` becomes `-1`. +: Redondea hacia el entero más cercano: `3.1` torna en `3`, `3.6` torna en `4` y `-1.1` torna en `-1`. -`Math.trunc` (not supported by Internet Explorer) -: Removes anything after the decimal point without rounding: `3.1` becomes `3`, `-1.1` becomes `-1`. +`Math.trunc` (no soportado por Internet Explorer) +: Remueve lo que haya tras el punto decimal sin redondear: `3.1` torna en `3`, `-1.1` torna en `-1`. -Here's the table to summarize the differences between them: +Aquí la tabla que resume las diferencias entre ellos: | | `Math.floor` | `Math.ceil` | `Math.round` | `Math.trunc` | |---|---------|--------|---------|---------| @@ -137,261 +137,261 @@ Here's the table to summarize the differences between them: |`-1.6`| `-2` | `-1` | `-2` | `-1` | -These functions cover all of the possible ways to deal with the decimal part of a number. But what if we'd like to round the number to `n-th` digit after the decimal? +Estas funciones cubren todas las posibles formas de lidiar con la parte decimal de un número. Pero ¿si quisiéramos redondear al enésimo `n-th` dígito tras el decimal? -For instance, we have `1.2345` and want to round it to 2 digits, getting only `1.23`. +Por ejemplo, tenemos `1.2345` y queremos redondearlo a 2 dígitos obteniendo solo `1.23`. -There are two ways to do so: +Hay dos formas de hacerlo: -1. Multiply-and-divide. +1. Multiplicar y dividir. - For example, to round the number to the 2nd digit after the decimal, we can multiply the number by `100`, call the rounding function and then divide it back. + Por ejemplo, para redondear el número a dos dígitos tras el decimal, podemos multiplicarlo por `100`, llamar la función de redondeo y volverlo a dividir. ```js run let num = 1.23456; alert( Math.floor(num * 100) / 100 ); // 1.23456 -> 123.456 -> 123 -> 1.23 ``` -2. The method [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) rounds the number to `n` digits after the point and returns a string representation of the result. +2. El método [toFixed(n)](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Number/toFixed) redondea el número a `n` dígitos después del punto decimal y devuelve una cadena que representa el resultado. ```js run let num = 12.34; alert( num.toFixed(1) ); // "12.3" ``` - This rounds up or down to the nearest value, similar to `Math.round`: + Este redondea hacia arriba o abajo al valor más cercano, similar a `Math.round`: ```js run let num = 12.36; alert( num.toFixed(1) ); // "12.4" ``` - Please note that result of `toFixed` is a string. If the decimal part is shorter than required, zeroes are appended to the end: + Ten en cuenta que el resultado de `toFixed` es una cadena. Si la parte decimal es más corta que lo requerido, se agregan ceros hasta el final: ```js run let num = 12.34; - alert( num.toFixed(5) ); // "12.34000", added zeroes to make exactly 5 digits + alert( num.toFixed(5) ); // "12.34000", con ceros agregados para dar exactamente 5 dígitos ``` - We can convert it to a number using the unary plus or a `Number()` call: `+num.toFixed(5)`. + Podemos convertirlo a número usando el operador unario más o llamando a `Number()`: `+num.toFixed(5)`. -## Imprecise calculations +## Cálculo impreciso -Internally, a number is represented in 64-bit format [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985), so there are exactly 64 bits to store a number: 52 of them are used to store the digits, 11 of them store the position of the decimal point (they are zero for integer numbers), and 1 bit is for the sign. +Internamente, un número es representado en formato de 64-bit [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985), donde hay exactamente 64 bits para almacenar un número: 52 de ellos son usados para almacenar los dígitos, 11 para almacenar la posición del punto decimal (son cero para los enteros), y 1 bit es para el signo. -If a number is too big, it would overflow the 64-bit storage, potentially giving an infinity: +Si un número es demasiado grande rebasaría el almacén de 64 bit, potencialmente dando infinito: ```js run alert( 1e500 ); // Infinity ``` -What may be a little less obvious, but happens quite often, is the loss of precision. +Lo que puede ser algo menos obvio, pero ocurre a menudo, es la pérdida de precisión. -Consider this (falsy!) test: +Considera este (¡falso!) test: ```js run alert( 0.1 + 0.2 == 0.3 ); // *!*false*/!* ``` -That's right, if we check whether the sum of `0.1` and `0.2` is `0.3`, we get `false`. +Es así, al chequear si la suma de `0.1` y `0.2` es `0.3`, obtenemos `false`. -Strange! What is it then if not `0.3`? +¡Qué extraño! ¿Qué es si no `0.3`? ```js run alert( 0.1 + 0.2 ); // 0.30000000000000004 ``` -Ouch! There are more consequences than an incorrect comparison here. Imagine you're making an e-shopping site and the visitor puts `$0.10` and `$0.20` goods into their chart. The order total will be `$0.30000000000000004`. That would surprise anyone. +¡Ay! Hay más consecuencias que una comparación incorrecta aquí. Imagina que estás haciendo un sitio de compras electrónicas y el visitante pone `$0.10` y `$0.20` en productos en su carrito. El total de la orden será `$0.30000000000000004`. Eso sorprendería a cualquiera. -But why does this happen? +¿Pero por qué pasa esto? -A number is stored in memory in its binary form, a sequence of ones and zeroes. But fractions like `0.1`, `0.2` that look simple in the decimal numeric system are actually unending fractions in their binary form. +Un número es almacenado en memoria en su forma binaria, una secuencia de bits, unos y ceros. Pero decimales como `0.1`, `0.2` que se ven simples en el sistema decimal son realmente fracciones sin fin en su forma binaria. -In other words, what is `0.1`? It is one divided by ten `1/10`, one-tenth. In decimal numeral system such numbers are easily representable. Compare it to one-third: `1/3`. It becomes an endless fraction `0.33333(3)`. +En otras palabras, ¿qué es `0.1`? Es un uno dividido por 10 `1/10`, un décimo. En sistema decimal es fácilmente representable. Compáralo con un tercio: `1/3`, se vuelve una fracción sin fin `0.33333(3)`. -So, division by powers `10` is guaranteed to work well in the decimal system, but division by `3` is not. For the same reason, in the binary numeral system, the division by powers of `2` is guaranteed to work, but `1/10` becomes an endless binary fraction. +Así, la división en potencias de diez garantizan un buen funcionamiento en el sistema decimal, pero divisiones por `3` no. Por la misma razón, en el sistema binario la división en potencias de `2` garantizan su funcionamiento, pero `1/10` se vuelve una fracción binaria sin fin. -There's just no way to store *exactly 0.1* or *exactly 0.2* using the binary system, just like there is no way to store one-third as a decimal fraction. +Simplemente no hay manera de guardar *exactamente 0.1* o *exactamente 0.2* usando el sistema binario, así como no hay manera de guardar un tercio en fracción decimal. -The numeric format IEEE-754 solves this by rounding to the nearest possible number. These rounding rules normally don't allow us to see that "tiny precision loss", so the number shows up as `0.3`. But beware, the loss still exists. +El formato numérico IEEE-754 resuelve esto redondeando al número posible más cercano. Estas reglas de redondeo normalmente no nos permiten percibir aquella "pequeña pérdida de precisión", pero existe. -We can see this in action: +Podemos verlo en acción: ```js run alert( 0.1.toFixed(20) ); // 0.10000000000000000555 ``` -And when we sum two numbers, their "precision losses" add up. +Y cuando sumamos dos números, se suman sus "pérdidas de precisión". -That's why `0.1 + 0.2` is not exactly `0.3`. +Y es por ello que `0.1 + 0.2` no es exactamente `0.3`. -```smart header="Not only JavaScript" -The same issue exists in many other programming languages. +```smart header="No solo JavaScript" +El mismo problema existe en muchos otros lenguajes de programación. -PHP, Java, C, Perl, Ruby give exactly the same result, because they are based on the same numeric format. +PHP, Java, C, Perl, Ruby dan exactamente el mismo resultado, porque ellos están basados en el mismo formato numérico. ``` -Can we work around the problem? Sure, the most reliable method is to round the result with the help of a method [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed): +¿Podemos resolver el problema? Seguro, la forma más confiable es redondear el resultado con la ayuda de un método. [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed): ```js run let sum = 0.1 + 0.2; alert( sum.toFixed(2) ); // 0.30 ``` -Please note that `toFixed` always returns a string. It ensures that it has 2 digits after the decimal point. That's actually convenient if we have an e-shopping and need to show `$0.30`. For other cases, we can use the unary plus to coerce it into a number: +Ten en cuenta que `toFixed` siempre devuelve un string. Esto asegura que tiene 2 dígitos después del punto decimal. Esto es en verdad conveniente si tenemos un sitio de compras y necesitamos mostrar `$0.30`. Para otros casos, podemos usar el + unario para forzar un número: ```js run let sum = 0.1 + 0.2; alert( +sum.toFixed(2) ); // 0.3 ``` -We also can temporarily multiply the numbers by 100 (or a bigger number) to turn them into integers, do the maths, and then divide back. Then, as we're doing maths with integers, the error somewhat decreases, but we still get it on division: +También podemos multiplicar temporalmente por 100 (o un número mayor) para transformarlos a enteros, hacer las cuentas, y volverlos a dividir. Como hacemos las cuentas con enteros el error se reduce, pero aún lo tenemos en la división: ```js run alert( (0.1 * 10 + 0.2 * 10) / 10 ); // 0.3 alert( (0.28 * 100 + 0.14 * 100) / 100); // 0.4200000000000001 ``` -So, multiply/divide approach reduces the error, but doesn't remove it totally. +Entonces, el enfoque de multiplicar/dividir reduce el error, pero no lo elimina por completo. -Sometimes we could try to evade fractions at all. Like if we're dealing with a shop, then we can store prices in cents instead of dollars. But what if we apply a discount of 30%? In practice, totally evading fractions is rarely possible. Just round them to cut "tails" when needed. +A veces podemos tratar de evitar los decimales del todo. Si estamos tratando con una tienda, podemos almacenar precios en centavos en lugar de dólares. Pero ¿y si aplicamos un descuento de 30%? En la práctica, evitar la parte decimal por completo es raramente posible. Simplemente se redondea y se corta el "rabo" decimal cuando es necesario. -````smart header="The funny thing" -Try running this: +````smart header="Algo peculiar" +Prueba ejecutar esto: ```js run -// Hello! I'm a self-increasing number! -alert( 9999999999999999 ); // shows 10000000000000000 +// ¡Hola! ¡Soy un número que se autoincrementa! +alert( 9999999999999999 ); // muestra 10000000000000000 ``` -This suffers from the same issue: a loss of precision. There are 64 bits for the number, 52 of them can be used to store digits, but that's not enough. So the least significant digits disappear. +Esto sufre del mismo problema: Una pérdida de precisión. Hay 64 bits para el número, 52 de ellos pueden ser usados para almacenar dígitos, pero no es suficiente. Entonces los dígitos menos significativos desaparecen. -JavaScript doesn't trigger an error in such events. It does its best to fit the number into the desired format, but unfortunately, this format is not big enough. +JavaScript no dispara error en tales eventos. Hace lo mejor que puede para ajustar el número al formato deseado, pero desafortunadamente este formato no es suficientemente grande. ```` -```smart header="Two zeroes" -Another funny consequence of the internal representation of numbers is the existence of two zeroes: `0` and `-0`. +```smart header="Dos ceros" +Otra consecuencia que sorprende de la representación interna de los números es la existencia de dos ceros: `0` y `-0`. -That's because a sign is represented by a single bit, so every number can be positive or negative, including a zero. +Esto es porque el signo es representado por un bit, así cada número puede ser positivo o negativo, incluyendo al cero. -In most cases the distinction is unnoticeable, because operators are suited to treat them as the same. +En la mayoría de los casos la distinción es imperceptible, porque los operadores están adaptados para tratarlos como iguales. ``` -## Tests: isFinite and isNaN +## Tests: isFinite y isNaN -Remember these two special numeric values? +¿Recuerdas estos dos valores numéricos especiales? -- `Infinity` (and `-Infinity`) is a special numeric value that is greater (less) than anything. -- `NaN` represents an error. +- `Infinity` (y `-Infinity`) es un valor numérico especial que es mayor (menor) que cualquier otra cosa. +- `NaN` ("No un Número") representa un error. -They belong to the type `number`, but are not "normal" numbers, so there are special functions to check for them: +Ambos pertenecen al tipo `number`, pero no son números "normales", así que hay funciones especiales para chequearlos: -- `isNaN(value)` converts its argument to a number and then tests it for being `NaN`: +- `isNaN(value)` convierte su argumento a número entonces testea si es `NaN`: ```js run alert( isNaN(NaN) ); // true alert( isNaN("str") ); // true ``` - But do we need this function? Can't we just use the comparison `=== NaN`? Sorry, but the answer is no. The value `NaN` is unique in that it does not equal anything, including itself: + Pero ¿necesitamos esta función? ¿No podemos simplemente usar la comparación `=== NaN`? Lo lamento pero la respuesta es no. El valor `NaN` es único en que no es igual a nada, incluyendo a sí mismo: ```js run alert( NaN === NaN ); // false ``` -- `isFinite(value)` converts its argument to a number and returns `true` if it's a regular number, not `NaN/Infinity/-Infinity`: +- `isFinite(value)` convierte su argumento a un número y devuelve `true` si es un número regular, no `NaN/Infinity/-Infinity`: ```js run alert( isFinite("15") ); // true - alert( isFinite("str") ); // false, because a special value: NaN - alert( isFinite(Infinity) ); // false, because a special value: Infinity + alert( isFinite("str") ); // false, porque es un valor especial: NaN + alert( isFinite(Infinity) ); // false, porque es un valor especial: Infinity ``` -Sometimes `isFinite` is used to validate whether a string value is a regular number: +A veces `isFinite` es usado para validar si un valor string es un número regular: ```js run let num = +prompt("Enter a number", ''); -// will be true unless you enter Infinity, -Infinity or not a number +// true salvo que ingreses Infinity, -Infinity o un valor no numérico alert( isFinite(num) ); ``` -Please note that an empty or a space-only string is treated as `0` in all numeric functions including `isFinite`. +Ten en cuenta que un valor vacío o un string de solo espacios es tratado como `0` en todas las funciones numéricas incluyendo `isFinite`. -```smart header="Compare with `Object.is`" +```smart header="Comparación con `Object.is`" -There is a special built-in method [Object.is](mdn:js/Object/is) that compares values like `===`, but is more reliable for two edge cases: +Hay un método especial incorporado [Object.is](mdn:js/Object/is) que compara valores como el `===`, pero es más confiable para dos casos extremos: -1. It works with `NaN`: `Object.is(NaN, NaN) === true`, that's a good thing. -2. Values `0` and `-0` are different: `Object.is(0, -0) === false`, it rarely matters, but these values technically are different. +1. Funciona con `NaN`: `Object.is(NaN, NaN) === true`, lo que es bueno. +2. Los valores `0` y `-0` son diferentes: `Object.is(0, -0) === false`. `false` es técnicamente correcto, porque internamente el número puede tener el bit de signo diferente incluso aunque todos los demás sean ceros. -In all other cases, `Object.is(a, b)` is the same as `a === b`. +En todos los demás casos, `Object.is(a, b)` es lo mismo que `a === b`. -This way of comparison is often used in JavaScript specification. When an internal algorithm needs to compare two values for being exactly the same, it uses `Object.is` (internally called [SameValue](https://tc39.github.io/ecma262/#sec-samevalue)). +Esta forma de comparación se usa a menudo en la especificación JavaScript. Cuando un algoritmo interno necesita comparar que dos valores sean exactamente iguales, usa `Object.is` (internamente llamado [SameValue](https://tc39.github.io/ecma262/#sec-samevalue)). ``` -## parseInt and parseFloat +## parseInt y parseFloat -Numeric conversion using a plus `+` or `Number()` is strict. If a value is not exactly a number, it fails: +La conversión numérica usando un más `+` o `Number()` es estricta. Si un valor no es exactamente un número, falla: ```js run alert( +"100px" ); // NaN ``` -The sole exception is spaces at the beginning or at the end of the string, as they are ignored. +La única exepción son los espacios al principio y al final del string, pues son ignorados. -But in real life we often have values in units, like `"100px"` or `"12pt"` in CSS. Also in many countries the currency symbol goes after the amount, so we have `"19€"` and would like to extract a numeric value out of that. +Pero en la vida real a menudo tenemos valores en unidades como `"100px"` o `"12pt"` en CSS. También el símbolo de moneda que en varios países va después del monto, tenemos `"19€"` y queremos extraerle la parte numérica. -That's what `parseInt` and `parseFloat` are for. +Para eso son `parseInt` y `parseFloat`. -They "read" a number from a string until they can't. In case of an error, the gathered number is returned. The function `parseInt` returns an integer, whilst `parseFloat` will return a floating-point number: +Estas "leen" el número desde un string hasta que dejan de poder hacerlo. En caso de error, devuelve el número que haya registrado hasta ese momento. La función `parseInt` devuelve un entero, mientras que `parseFloat` devolverá un punto flotante: ```js run alert( parseInt('100px') ); // 100 alert( parseFloat('12.5em') ); // 12.5 -alert( parseInt('12.3') ); // 12, only the integer part is returned -alert( parseFloat('12.3.4') ); // 12.3, the second point stops the reading +alert( parseInt('12.3') ); // 12, devuelve solo la parte entera +alert( parseFloat('12.3.4') ); // 12.3, el segundo punto detiene la lectura ``` -There are situations when `parseInt/parseFloat` will return `NaN`. It happens when no digits could be read: +Hay situaciones en que `parseInt/parseFloat` devolverán `NaN`. Ocurre cuando no hay dígitos a ser leidos: ```js run -alert( parseInt('a123') ); // NaN, the first symbol stops the process +alert( parseInt('a123') ); // NaN, el primer símbolo detiene la lectura ``` -````smart header="The second argument of `parseInt(str, radix)`" -The `parseInt()` function has an optional second parameter. It specifies the base of the numeral system, so `parseInt` can also parse strings of hex numbers, binary numbers and so on: +````smart header="El segundo argumento de `parseInt(str, radix)`" +La función `parseInt()` tiene un segundo parámetro opcional. Este especifica la base de sistema numérico, entonces `parseInt` puede también analizar cadenas de numeros hexa, binarios y así: ```js run alert( parseInt('0xff', 16) ); // 255 -alert( parseInt('ff', 16) ); // 255, without 0x also works +alert( parseInt('ff', 16) ); // 255, sin 0x también funciona alert( parseInt('2n9c', 36) ); // 123456 ``` ```` -## Other math functions +## Otras funciones matemáticas -JavaScript has a built-in [Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) object which contains a small library of mathematical functions and constants. +JavaScript tiene un objeto incorporado [Math](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math) que contiene una pequeña biblioteca de funciones matemáticas y constantes. -A few examples: +Unos pocos ejemplos: `Math.random()` -: Returns a random number from 0 to 1 (not including 1) +: Devuelve un número aleatorio entre 0 y 1 (no incluyendo 1) ```js run alert( Math.random() ); // 0.1234567894322 alert( Math.random() ); // 0.5435252343232 - alert( Math.random() ); // ... (any random numbers) + alert( Math.random() ); // ... (cualquier número aleatorio) ``` `Math.max(a, b, c...)` / `Math.min(a, b, c...)` -: Returns the greatest/smallest from the arbitrary number of arguments. +: Devuelve el mayor/menor de entre una cantidad arbitraria de argumentos. ```js run alert( Math.max(3, 5, -10, 0, 1) ); // 5 @@ -399,36 +399,36 @@ A few examples: ``` `Math.pow(n, power)` -: Returns `n` raised the given power +: Devuelve `n` elevado a la potencia `power` dada ```js run - alert( Math.pow(2, 10) ); // 2 in power 10 = 1024 + alert( Math.pow(2, 10) ); // 2 elevado a la potencia de 10 = 1024 ``` -There are more functions and constants in `Math` object, including trigonometry, which you can find in the [docs for the Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) object. +Hay más funciones y constantes en el objeto `Math`, incluyendo trigonometría, que puedes encontrar en la [documentación del objeto Math](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math). -## Summary +## Resumen -To write big numbers: +Para escribir grandes números: -- Append `"e"` with the zeroes count to the number. Like: `123e6` is `123` with 6 zeroes. -- A negative number after `"e"` causes the number to be divided by 1 with given zeroes. That's for one-millionth or such. +- Agregar `"e"` con la cantidad de ceros al número. Como: `123e6` es `123` con 6 ceros. +- Un número negativo después de `"e"` hace que el número sea dividido por 1 seguido de la cantidad dada de ceros. Como un millonésimo y tales. -For different numeral systems: +Para diferentes sistemas numéricos: -- Can write numbers directly in hex (`0x`), octal (`0o`) and binary (`0b`) systems -- `parseInt(str, base)` parses an integer from any numeral system with base: `2 ≤ base ≤ 36`. -- `num.toString(base)` converts a number to a string in the numeral system with the given `base`. +- Se pueden escribir números directamente en sistemas hexa (`0x`), octal (`0o`) y binario (`0b`). +- `parseInt(str, base)` convierte un string a un entero en el sistema numérico de la `base` dada, `2 ≤ base ≤ 36`. +- `num.toString(base)` convierte un número a string en el sistema de la `base` dada. -For converting values like `12pt` and `100px` to a number: +Para convertir valores como `12pt` y `100px` a un número: -- Use `parseInt/parseFloat` for the "soft" conversion, which reads a number from a string and then returns the value they could read before the error. +- Usa `parseInt/parseFloat` para una conversión "suave", que lee un número desde un string y devuelve el valor del número que pudiera leer antes de encontrar error. -For fractions: +Para números decimales: -- Round using `Math.floor`, `Math.ceil`, `Math.trunc`, `Math.round` or `num.toFixed(precision)`. -- Make sure to remember there's a loss of precision when working with fractions. +- Redondea usando `Math.floor`, `Math.ceil`, `Math.trunc`, `Math.round` o `num.toFixed(precision)`. +- Asegúrate de recordar que hay pérdida de precisión cuando se trabaja con decimales. -More mathematical functions: +Más funciones matemáticas:: -- See the [Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) object when you need them. The library is very small, but can cover basic needs. +- Revisa el documento del objeto [Math](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math) cuando las necesites. La biblioteca es pequeña pero puede cubrir las necesidades básicas. pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy