---
# System prepended metadata

title: 從頭開始 javascript 的學習紀錄 語法(2)
tags: [JavaScript 學習歷程]

---

# 從頭開始 javascript 的學習紀錄 語法(2)
###### tags: `JavaScript 學習歷程`

## 未定義元素
```javascript=
let ar = [1,,,,58];               //[ 1, <3 empty items>, 58 ]
console.log(ar);
```

## 函式定義運算式
```javascript=
let square = function(x){
    return x * x
};
console.log(square(5))            //25
```                
--------------------------------------
## 述句
```javascript=
//if......else (else if) and switch
let x = 5;
if (x == 3){
    x = 2;
    console.log(x);
};
console.log(x)
------------------------------------------------------------------------
let x = 5;
switch(x){
    case 5:
        console.log(6);
        break;
    case 6:
        console.log(555);
        break;
}
```

## 迴圈
```javascript=
//while
let x = 5;
while (x = 5){
    x -= 1;
    console.log(x);
    break;
};
------------------------------------------------------------------------
//do......while
let x = 5;
do{
    x -= 1;
    console.log(x);
    break;
}while(x = 5);
------------------------------------------------------------------------
//for
let x = 5;
for (x = 5; x > 1; x--){
    console.log(x);
}
------------------------------------------------------------------------
//for......of
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0;
for(let x of data){
    sum += x;
}
console.log(sum);
```
## 函式
```javascript=
function text(){
    console.log('sssss');
}
text()
//const f = text;
//f();
------------------------------------------------------------------------
//指派物件
const x = {};
x.f = text;
x.f();
```
## 引數
```javascript=
function text(a, b){
    console.log(a + b);
}

text(1, 5);
```
## 箭頭函式
```javascript=
const x = () => "hello"; 
console.log(x());                 //hello
```

## 陣列
```javascript=
//經典的sort
const x = [5, 4, 3, 2, 1];
x.sort()
console.log(x)
```
## 物件
```javascript=
class car{
    text(){
        return "hello";
    }
}
const a = new car();      //建構
console.log(a.text());    //hello
------------------------------------------------------------------------
//使用簡單的this
//換成Python的self?可能比較好理解
class car{
    text(a, b){
        this.a = a;
        this.b = b;
        return a + b;
    }
}
const a = new car();
console.log(a.text(2, 3));
```
## 簡單遞迴
```javascript=
const fact = function(x) {
    return (x <= 1)? 1 : x * fact(x-1);
};
console.log(fact(3));        //6
```
{%hackmd S1DMFioCO %}
