JavaScript 直播班
何時出現 undefined?
let a;
console.log(a); // output: undefined
JavaScript 編譯時會先將所有變數掃過一輪,先畫出記憶體空間後再賦予值到變數。因此使用 var 宣告變數,會出現在宣告變數前就嘗試取值,但因為還沒賦予值,而出現 undefined 訊息。
另外,因為有先畫出空間,代表 JavaScript 知道有這個變數,只是還沒到宣告那一行,因此不會出現沒有定義變數訊息 a is not defined
。
console.log(a); // output: undefined
var a = 1;
console.log(a); // output: 1
但如果利用 let 宣告變數,錯誤訊息會換成 Uncaught ReferenceError: Cannot access 'a' before initialization
。
何時出現 null?
let a = null; // 宣告變數時賦予值為空值
let b = 1;
b = null; // 將原本變數值清空
undefined 與 null 型別
兩者型別如名。如下:
let a;
let b = null;
console.log(a, b); // output: undefined null
參考資料
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing