Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Type Conversions#57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
lizzie136 merged 8 commits intojavascript-tutorial:masterfromtikoflano:master
Aug 22, 2019
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,9 +16,9 @@ null + 1 = 1 // (5)
undefined + 1 = NaN // (6)
```

1.The addition with a string `"" + 1`converts`1`to astring: `"" + 1 = "1"`,and then we have`"1" + 0`,the same rule is applied.
2.The subtraction `-` (like most math operations) only works with numbers, it converts an emptystring `""`to `0`.
3.The addition with a stringappends the number `5`to the string.
4.The subtraction always converts to numbers, so it makes`" -9 "`a number `-9` (ignoring spaces around it).
5. `null`becomes `0` after the numeric conversion.
6. `undefined`becomes `NaN` after the numeric conversion.
1.La suma con un string `"" + 1`convierte el número`1`a unstring: `"" + 1 = "1"`,luego tenemos`"1" + 0`,la misma regla es aplicada.
2.La resta `-` (como la mayoría de las operaciones matemáticas) sólo funciona con números, convierte unstringvacío`""`a `0`.
3.La suma con un stringañade el número `5`al string.
4.La resta siempre convierte a números, por lo que convierte`" -9 "`al número `-9` (ignorando los espacios alrededor del string).
5.La conversión a número convierete`null`en `0`.
6.La conversión a número convierete`undefined`en `NaN`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
importance: 5
importancia: 5

---

#Type conversions
#Conversiones de Tipos

What are results of these expressions?
¿Cuáles son los resultados de estas expresiones?

```js no-beautify
"" + 1 + 0
Expand All@@ -23,4 +23,4 @@ null + 1
undefined + 1
```

Think well, write down and then compare with the answer.
Piensa cuidadosamente, luego escribe los resultados y compáralos con la respuesta.
116 changes: 57 additions & 59 deletions1-js/02-first-steps/06-type-conversions/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,160 +1,158 @@
#Type Conversions
#Conversiones de Tipos

Most of the time, operators and functions automatically convert the values given to them to the right type. This is called "type conversion".
La mayoría de las veces, los operadores y funciones convierten automáticamente los valores que se les pasan al tipo correcto. Esto es llamado "conversión de tipo".

For example, `alert`automatically converts any value toa stringto show it. Mathematical operations convert values to numbers.
Por ejemplo, `alert`convierte automáticamente cualquier valora stringpara mostrarlo. Las operaciones matemáticas convierten los valores a números.

There are also cases when we need to explicitly convert a value to the expected type.
También hay casos donde necesitamos convertir de manera explícita un valor al tipo esperado.

```smart header="Not talking about objects yet"
In this chapter, we won't cover objects. Instead, we'll study primitives first. Later, after we learn about objects, we'll see how object conversion works in the chapter <info:object-toprimitive>.
```smart header="Aún no hablamos de objetos"
En este capítulo no cubriremos los objetos. Estudiaremos los valores primitivos primero. Luego, después de haber hablado sobre objetos, veremos cómo funciona la conversión de objetos en este capítulo <info:object-toprimitive>.
```

## ToString

String conversion happens when we need the string form of a value.
La conversión a string ocurre cuando necesitamos la representación en forma de texto de un valor.

For example, `alert(value)`does it to show the value.
Por ejemplo, `alert(value)`lo hace para mostrar el valor como texto.

We can also call the`String(value)`function to convert a value to a string:
También podemos llamar a la función`String(value)`para convertir un valor a string:

```js run
let value = true;
alert(typeof value); // boolean

*!*
value = String(value); //now valueis a string "true"
value = String(value); //ahora valuees el string "true"
alert(typeof value); // string
*/!*
```

String conversion is mostly obvious. A`false`becomes`"false"`, `null`becomes `"null"`, etc.
La conversión a string es bastante obvia. El boolean`false`se convierte en`"false"`, `null`en `"null"`, etc.

## ToNumber

Numeric conversion happens in mathematical functions and expressions automatically.
La conversión numérica ocurre automáticamente en funciones matemáticas y expresiones.

For example, when division `/` is applied to non-numbers:
Por ejemplo, cuando se dividen valores no numéricos usando `/`:

```js run
alert( "6" / "2" ); // 3, stringsare converted to numbers
alert( "6" / "2" ); // 3,losstringsson convertidos a números
```

We can use the `Number(value)` function to explicitly convert a `value` to a number:
Podemos usar la función `Number(value)` para convertir de forma explícita un valor a un número:

```js run
let str = "123";
alert(typeof str); // string

let num = Number(str); //becomes a number 123
let num = Number(str); //se convierte en 123

alert(typeof num); // number
```
La conversión explícita es requerida usualmente cuando leemos un valor desde una fuente basada en texto, como lo son los campos de texto en los formularios, pero que esperamos que contengan un valor numérico.

Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered.

If the string is not a valid number, the result of such a conversion is `NaN`. For instance:
Si el string no es un número válido, el resultado de la conversión será `NaN`. Por ejemplo:

```js run
let age = Number("an arbitrary string instead of a number");
let age = Number("un texto arbitrario en vez de un número");

alert(age); // NaN,conversion failed
alert(age); // NaN,conversión fallida
```

Numeric conversion rules:
Reglas de conversión numérica:

|Value |Becomes... |
|Valor |Se convierte en... |
|-------|-------------|
|`undefined`|`NaN`|
|`null`|`0`|
|<code>true&nbsp;and&nbsp;false</code> | `1`and `0` |
| `string` |Whitespaces from the start and end are removed. If the remainingstringis empty, the result is `0`. Otherwise, the number is "read" from thestring.An errorgives `NaN`. |
|<code>true&nbsp;and&nbsp;false</code> | `1`y `0` |
| `string` |Se eliminan los espacios al inicio y final del texto. Si elstringresultante es vacío, el resultado es `0`, en caso contario el número es "leído" delstring.Un errordevuelve `NaN`. |

Examples:

```js run
alert( Number(" 123 ") ); // 123
alert( Number("123z") ); // NaN (errorreading a number at "z")
alert( Number("123z") ); // NaN (erroral leer un número en "z")
alert( Number(true) ); // 1
alert( Number(false) ); // 0
```

Please note that`null`and `undefined`behave differently here: `null`becomes zero while `undefined`becomes `NaN`.
Ten en cuenta que`null`y `undefined`se comportan de distinta manera aquí: `null`se convierte en `0` mientras que `undefined`se convierte en `NaN`.

````smart header="Addition '+'concatenates strings"
Almost all mathematical operations convert values to numbers. Anotableexception is addition `+`.If one of the added values is a string,the other one is also converted to a string.
````smart header="Adición '+'concatena strings"
Casi todas las operaciones matemáticas convierten valores a números. Una excepciónnotablees la suma `+`.Si uno de los valores sumados es un string,el otro valor es convertido a string.

Then, it concatenates (joins) them:
Luego, los concatena (une):

```js run
alert( 1 + '2' ); // '12' (stringto the right)
alert( '1' + 2 ); // '12' (stringto the left)
alert( 1 + '2' ); // '12' (stringa la derecha)
alert( '1' + 2 ); // '12' (stringa la izqueirda)
```

This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
Esto ocurre solo si al menos uno de los argumentos es un string, en caso contario los valores son convertidos a número.
````

## ToBoolean

Boolean conversion is the simplest one.
La conversión a boolean es la más simple.

It happens in logical operations (later we'll meet condition tests and other similar things) but can also be performed explicitly with a call to `Boolean(value)`.
Ocurre en operaciones lógicas (más adelante veremos test condicionales y otras cosas similares) pero también puede realizarse de forma explícita llamando a la función `Boolean(value)`.

The conversion rule:
Las reglas de conversión:

-Values that are intuitively "empty",like `0`,an empty string, `null`, `undefined`,and `NaN`,become `false`.
-Other values become `true`.
-Los valores que son intuitivamente "vacíos",como `0`,`""`, `null`, `undefined`,y `NaN`,se convierten en `false`.
-Otros valores se convierten en `true`.

For instance:
Por ejemplo:

```js run
alert( Boolean(1) ); // true
alert( Boolean(0) ); // false

alert( Boolean("hello") ); // true
alert( Boolean("hola") ); // true
alert( Boolean("") ); // false
```

````warn header="Please note: the stringwith zero`\"0\"`is `true`"
Some languages (namely PHP)treat `"0"`as `false`.But in JavaScript,a non-emptystringis always `true`.
````warn header="Ten en cuenta: el stringcon un cero`\"0\"`es `true`"
Algunos lenguajes (como PHP)tratan `"0"`como `false`.Pero en JavaScript,unstringno vacío es siempre `true`.

```js run
alert( Boolean("0") ); // true
alert( Boolean(" ") ); //spaces, also true (any non-emptystringis true)
alert( Boolean(" ") ); //sólo espacios, también true (cualquierstringno vacío es true)
```
````


##Summary
##Resumen

The three most widely used type conversions are to string,to number, and to boolean.
Las tres conversiones de tipo más usadas son a string,a número y a boolean.

**`ToString`** --Occurs when we output something. Can be performed with `String(value)`.The conversion to stringis usually obvious for primitive values.
**`ToString`** --Ocurre cuando se muestra algo. Se puede realizar con `String(value)`.La conversión a stringes usualmente obvia para los valores primitivos.

**`ToNumber`** --Occurs in math operations. Can be performed with `Number(value)`.
**`ToNumber`** --Ocurre en operaciones matemáticas. Se puede realizar con `Number(value)`.

The conversion follows the rules:
La conversión sigue las reglas:

|Value |Becomes... |
|Valor |Se convierte en... |
|-------|-------------|
|`undefined`|`NaN`|
|`null`|`0`|
|<code>true&nbsp;/&nbsp;false</code> | `1 / 0` |
| `string` |The stringis read "as is",whitespaces from both sides are ignored. An emptystringbecomes`0`.An errorgives `NaN`. |
| `string` |El stringes leído "como es",los espacios en blanco tanto al inicio como al final son ignorados. Unstringvacío se convierte en`0`.Un errorentrega `NaN`. |

**`ToBoolean`** --Occurs in logical operations. Can be performed with `Boolean(value)`.
**`ToBoolean`** --Ocurren en operaciones lógicas. Se puede realizar con `Boolean(value)`.

Follows the rules:
Sigue las reglas:

|Value |Becomes... |
|Valor |Se convierte en... |
|-------|-------------|
|`0`, `null`, `undefined`, `NaN`, `""` |`false`|
|any other value| `true` |
|cualquier otro valor| `true` |


Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
La mayoría de estas reglas son fáciles de entender y recordar. Las excepciones más notables donde la gente suele cometer errores son:

- `undefined`is `NaN`as a number, not `0`.
- `"0"`and space-only strings like`" "`aretrue as a boolean.
- `undefined`es `NaN`como número, no `0`.
- `"0"`y textos que solo contienen espacios como`" "`son `true` como boolean.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Quedaría mejor cadenas en lugar de textos

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

En todo el resto del artículo se usa la palabra "texto". Creo que "cadena" o "cadena de caracteres" puede confundir al lector ya que no se ha explicado lo que es.


Objects aren't covered here. We'll return to them later in the chapter <info:object-toprimitive>that is devoted exclusively to objects after we learn more basic things about JavaScript.
Los objetos no son cubiertos aquí. Volveremos a ellos más tarde en el capítulo <info:object-toprimitive>que está dedicado exclusivamente a objetos después de que aprendamos más cosas básicas sobre JavaScript.

[8]ページ先頭

©2009-2025 Movatter.jp