xia的小窩

一起來coding和碼字吧

0%

從頭開始javascript的學習紀錄-語法-2

未定義元素

1
2
let ar = [1,,,,58];               //[ 1, <3 empty items>, 58 ]
console.log(ar);

函式定義運算式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
}

迴圈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//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);

函式

1
2
3
4
5
6
7
8
9
10
11
function text(){
console.log('sssss');
}
text()
// const f = text;
//f();
// ------------------------------------------------------------------------
//指派物件
const x = {};
x.f = text;
x.f();

引數

1
2
3
4
5
function text(a, b){
console.log(a + b);
}

text(1, 5);

箭頭函式

1
2
const x = () => "hello"; 
console.log(x()); //hello

陣列

1
2
3
4
//經典的sort
const x = [5, 4, 3, 2, 1];
x.sort()
console.log(x)

物件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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));

簡單遞迴

1
2
3
4
const fact = function(x) {
return (x <= 1)? 1 : x * fact(x-1);
};
console.log(fact(3)); //6