JavaScript筆記
列印字串
列印字串使用console.log(),像是c語言中的printf
範例:
Hi
hello world
console.log("Hi");
a = "hollo";
b = "world";
console.log(a,b);
宣告變數
宣告變數var (什麼型態都可以宣告),而加var是區域變數,不加是全域變數。
var a = 3;
var b = hi;
for迴圈
for迴圈裡的continue,會跳過這一輪繼續執行下一輪迴圈;而break會直接跳出迴圈。
範例:
1
3
4
for (i=1;i<=6;i++) {
if (i == 2) continue;
if (i == 5) break;
console.log(i);
}
字串相加
for迴圈裡的continue,會跳過這一輪繼續執行下一輪迴圈;而break會直接跳出迴圈。
範例:
helloworld
"hello"+"world"
取字串長度
字串.length
範例:
10
a = "helloworld";
a.length;
取字串
字串名稱.substr(起始點,長度)從起始點開始取出多少長度的字串。
字串名稱.substring(起始點,終止點)取出從起始點開始到終止點之前的字串。(不包含終止點)。
範例:
hello
world
a = "helloworld";
a.substr(0,5);
a.substring(5,10);
字串大小寫轉換
轉小寫:
字串.toLowerCase();
轉大寫:
字串.toUpperCase();
範例:
hello
HELLO
a = "hElLo";
a.toLowerCase();
a.toUpperCase();
字串相接
第一個字串.concat(第二個字串)
範例:
helloworld
a = "hello";
b = "world";
a.concat(b);
取字元
字串.charAt(N)取出第N個字元
範例:
l
a = "hello";
a.charAt(3);
切出字串
字串.slice(N)切出起始點之後的內容
範例:
ello
a = "hello";
a.slice(1);
推入陣列
陣列.push(N)把N推入陣列尾端
範例:
a=[0,1,2,3]
a=[0,1,2]
a.push(3);
陣列相接
陣列1.concat(陣列2)將兩個陣列相接,不會改變陣列1的內容
範例:
[ 1, 2, 3, 4, 5, 6]
a = [1,2,3];
a.concat([4,5,6]);
陣列轉成字串
陣列.join()把一個陣列接成一個字串
範例:
"1,2,3"
a = [1,2,3];
a.join();
取出陣列元素
陣列.shift()把陣列最前面的元素取出來
範例:
1
[ 2, 3 ]
a = [1,2,3];
a.shift();//取出1
console.log(a);//列印a陣列
參考資料:
陳鍾誠教授:JavaScript 基礎
陳鍾誠的課程社團
Favicon