xia的小窩

一起來coding和碼字吧

0%

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

註解使用的是 // 的方式

1
//

保留字

數字

數字方面,javascript的數字允許精確表達2^53 ~ 2^-53之間

Math,在ES6加入了更多定義上的函式

1
2
console.log(Math.pow(2, 8)) //256 (2^8)
console.log(Math.cbrt(8)) // 2 (立方根)

字串

1
2
3
4
5
let s = "hello world";

console.log(s.length)
//console.log(`${s}`) (format)
//console.log(s.slice(1, 4)) (切割)

全域物件

1.常數
2.函式。p.s. isNaNA()……等
3.建構器函式,Date(), parseInt()……等
4.Math, Json 之類的全域物件

不可變的原始值和可變的物件

1
2
3
4
let s = "hello world";

console.log(s.toUpperCase()); //HELLO WORLD
console.log(s) //hello world

陣列

1
2
3
4
5
6
7
8
9
10
11
//copy the array
let s = ["1", "2"];
let a = [];
for (let i = 0; i < s.length; i++){
a[i] = s[i];
}
console.log(a)

//but, there was a smart method
let c = Array.from(s);
console.log(c);

型別轉換

1
2
3
4
console.log(10+"x");     //10x
console.log("2"*"5"); //10
let n = 1 - "x"
console.log(n+"hello"); //NaNhello

明確轉換

1
2
3
4
5
6
console.log(Number("3"));        //3
console.log(String(false)); //false
//console.log(false.toString())
console.log(Boolean([])); //true
console.log(parseInt("3 re")); //3
console.log(parseFloat(" 3.5")); //3.5

Let, Const

1
2
3
4
5
6
//宣告變數
let i;
let j, sum; //.......
//宣告常數而非變數
const a = 5;
//也就是說,let 的值可以被更改,const不行

務必避免重複宣告

1
2
3
4
5
6
const x = 5;
if (x == 5){
let x = 2;
console.log(x); //x = 2,block scope區塊範疇
}
console.log(x); //x = 5,global scope全域範疇

解構指定(右手邊給左手邊)

1
2
3
4
5
6
7
let [x, y] = [1];         //x = 1, y = undefined
let [x, y] = [1, 2, 3] //x = 1, y = 2

let a = {x:1, y:2};
for(const[name, value] of Object.entries(a)){
console.log(`${name} : ${value}`);
}