Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type Conversions #16

Merged
merged 2 commits into from
Aug 27, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ null + 1 = 1 // (5)
undefined + 1 = NaN // (6)
```

1. The addition with a string `"" + 1` converts `1` to a string: `"" + 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 empty string `""` to `0`.
3. The addition with a string appends 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. 字串的加法 `"" + 1` 會轉換 `1` 為字串:`"" + 1 = "1"`,然後得到 `"1" + 0` 再利用一樣的規則。
2. 減法 `-` (就像多數數學運算) 只能用在數值上,它將空字串 `""` 轉成 `0`。
3. 字串的加法會將數值 `5` 視為字串接在其後。
4. 減法總是會轉換至數值,所以把 `" -9 "` 變成數值 `-9` (忽略環繞的空白)。
5. `null` 經由數值轉換變成 `0`。
6. `undefined` 經由數值轉換變成 `NaN`。

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Type conversions
# 類型轉換

What are results of these expressions?
這些表達式的結果會是什麼?

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

Think well, write down and then compare with the answer.
好好想一下,把結果寫下來並和答案對照看看。

115 changes: 57 additions & 58 deletions 1-js/02-first-steps/06-type-conversions/article.md
Original file line number Diff line number Diff line change
@@ -1,111 +1,111 @@
# Type Conversions
# 類型轉換

Most of the time, operators and functions automatically convert the values given to them to the right type.
大多時候,運算子和函式會自動轉換給予它們的值為正確類型。

For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers.
例如,`alert` 自動將任何值轉換成字串並顯示,數學運算子會把值轉換成數值。

There are also cases when we need to explicitly convert a value to the expected type.
當然某些情況我們得明確地轉換一個值至預期的類型。

```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="還沒開始談到物件類型"
在這章節,我們將不會轉換物件類型,我們會從原生類型開始說起。等晚點我們學完物件後,會在章節 <info:object-toprimitive> 中談到物件是如何被轉換的。
```

## ToString

String conversion happens when we need the string form of a value.
字串轉換發生在我們需要得到某個值的字串型態時。

For example, `alert(value)` does it to show the value.
例如,`alert(value)` 就做這件事並顯示其值。

We can also call the `String(value)` function to convert a value to a string:
我們也可以呼叫 `String(value)` 函式把一個值轉為字串:

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

*!*
value = String(value); // now value is a string "true"
value = String(value); // 現在 value 是一個 "true" 字串
alert(typeof value); // string
*/!*
```

String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc.
字串轉換通常很直觀,一個 `false` 變成 `"false"``null` 變成 `"null"` 等。

## ToNumber

Numeric conversion happens in mathematical functions and expressions automatically.
數值轉換自動發生在數學運算函式和表達式。

For example, when division `/` is applied to non-numbers:
例如,當除法 `/` 被運用在非數值上時:

```js run
alert( "6" / "2" ); // 3, strings are converted to numbers
alert( "6" / "2" ); // 3,字串被轉成數值
```

We can use the `Number(value)` function to explicitly convert a `value` to a number:
我們可以使用 `Number(value)` 函式來明確地轉換一個 `value` 為一個數值:

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

let num = Number(str); // becomes a number 123
let num = Number(str); // 變成數值 123

alert(typeof num); // number
```

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:
如果該字串不是個有效的數值,轉換的結果會是 `NaN`,如:

```js run
let age = Number("an arbitrary string instead of a number");
let age = Number("任何非數字的字串");

alert(age); // NaN, conversion failed
alert(age); // NaN,轉換失敗
```

Numeric conversion rules:
數值轉換規則:

| Value | Becomes... |
| | 會變成... |
|-------|-------------|
|`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 remaining string is empty, the result is `0`. Otherwise, the number is "read" from the string. An error gives `NaN`. |
|<code>true&nbsp;&nbsp;false</code> | `1` `0` |
| `string` | 先去除頭尾空白,如果剩下的字串是空字串則結果是 `0`,否則數值將被從剩下的字串中被 "讀取",此時若有錯誤將產生 `NaN` |

Examples:
例子:

```js run
alert( Number(" 123 ") ); // 123
alert( Number("123z") ); // NaN (error reading a number at "z")
alert( Number("123z") ); // NaN ("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`.
請注意 `null` `undefined` 的行為在此處不同:`null` 會變成零,而 `undefined` 會變成 `NaN`

````smart header="Addition '+' concatenates strings"
Almost all mathematical operations convert values to numbers. A notable exception is addition `+`. If one of the added values is a string, the other one is also converted to a string.
````smart header="加法 '+' 連接字串們"
幾乎所有數學運算子都會將值轉成數值,而加法 `+` 是個值得一提的例外。如果加法某側運算元是個字串,另一側將也會被轉換成字串。

Then, it concatenates (joins) them:
然後兩者將被連接:

```js run
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
alert( 1 + '2' ); // '12' (右側為字串)
alert( '1' + 2 ); // '12' (左側為字串)
```

This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
這只發生在當至少一側的引數是字串時,否則值都會被轉為數值。
````

## ToBoolean

Boolean conversion is the simplest one.
布林轉換是最簡單的一個。

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)`.
它發生在邏輯運算 (晚點我們將看到條件判斷和其它類似的東西),但也可以經由呼叫 `Boolean(value)` 來明確地轉換。

The conversion rule:
轉換規則是:

- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`.
- Other values become `true`.
- 直觀上是 "空白" 的值,像是 `0`、空字串、`null``undefined` `NaN`,都會變成 `false`
- 其他值變成 `true`

For instance:
例如:

```js run
alert( Boolean(1) ); // true
Expand All @@ -115,46 +115,45 @@ alert( Boolean("hello") ); // true
alert( Boolean("") ); // false
```

````warn header="Please note: the string with zero `\"0\"` is `true`"
Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`.
````warn header="請注意:包含零的字串 `\"0\"` 將會是 `true`"
某些語言 (如 PHP) `"0"` `false`,但在 JavaScript 中,一個非空字串都會是 `true`

```js run
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
alert( Boolean(" ") ); // 空白,也是 true (任何非空字串都是 true)
```
````

## 總結

## Summary
三種最為廣泛使用的類型轉換是:轉字串、轉數值和轉布林。

The three most widely used type conversions are to string, to number, and to boolean.
**`ToString`** - 用於當我們輸出某些東西時,可使用 `String(value)` 來轉換,原生值的字串的轉換通常是很直觀的。

**`ToString`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
**`ToNumber`** - 用於數學運算,可使用 `Number(value)` 來轉換。

**`ToNumber`** -- Occurs in math operations. Can be performed with `Number(value)`.
按照以下規則轉換:

The conversion follows the rules:

| Value | Becomes... |
| 值 | 會變成... |
|-------|-------------|
|`undefined`|`NaN`|
|`null`|`0`|
|<code>true&nbsp;/&nbsp;false</code> | `1 / 0` |
| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. |
| `string` | 字串 "依原樣" 讀取並忽略頭尾空白,若為空字串則為 `0`,有錯誤則成為 `NaN` |

**`ToBoolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
**`ToBoolean`** - 用於邏輯運算,可使用 `Boolean(value)` 來轉換。

Follows the rules:
規則是:

| Value | Becomes... |
| | 會變成... |
|-------|-------------|
|`0`, `null`, `undefined`, `NaN`, `""` |`false`|
|any other value| `true` |
|其它值| `true` |

這些規則大多容易理解記憶,值得一提的是,大家常常在這些地方犯錯:

Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
- `undefined` 轉成數值是 `NaN` 而非 `0`。
- `"0"` 和像是 `" "` 這種只包含空白的字串在轉成布林時是 true。

- `undefined` is `NaN` as a number, not `0`.
- `"0"` and space-only strings like `" "` are true as a boolean.
在此沒提到物件的轉換,我們將會晚點在專門介紹物件的章節 <info:object-toprimitive> 中提及,先讓我們了解更多 JavaScript 中基礎的內容。

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.