Intro to JavaScript
Hours: 18 hrs
Instructor : Andy Tseng
Module 1. 測試及除錯工具
Module 2. 使用 script 標籤
Module 3. 常數和變數宣告
1-1: Chrome開發者工具 1-2: Console面板 1-3: Network面板
2-1: DOM簡介
2-2: 動態新增頁面標籤內容
2-3: 取得標籤元素
document.head
|
回傳 <head> 元件
|
document.body
|
回傳 <body> 元件
|
document.scripts
|
回傳 <scripts> 元件
|
document.title
|
回傳 <title> 元件
|
Camel Case 駝峰式 :
Snake Case 蛇式 :
var: 變數
let: 變數
const: 常數 -> 不會重新被定義
Demo on nb or DevTools
- // console.log(0o23) // 舊的 8 進位用法, 不建議使用 - console.log(0o23) // 8 進位 - console.log(0x23) // 16 進位 - console.log(0b1111) // 2 進位 - console.log(2e5) // 科學表示法
Let's Test on DevTools or Appendix on nb
1. 域不一樣!
2.
Let's test on DevTools
if(true){
//Start of the Block scope
let b = 'Hi I am in the Block';
//End of the Block scope
}
console.log(b);
//ReferenceError
(function(){
var s = 'Hi I am in the Function';
}())
console.log(s)
//ReferenceError
- Boolean // 布林 - Number // 數字 - String // 字串 - null // 空值 - undefined // 空值,也可視為一個型態 - true // 常數,不可作為變數名稱 (Js 開頭為小寫,與 Python 不同) - false // 常數,不可作為變數名稱 (Js 開頭為小寫,與 Python 不同)
我們來在 DevTools 測試 - true = 100
- 12 = 33 // 不能使用 因為 12 不是變數
- 0xFF0000 //色碼 RGB 所以這個是紅色
- 2e3
- 2E3 //大小寫皆可
- 2E-3 //後面是負的代表示 10^-3次方 2*0.001
- Number.MAX_SAFE_INTEGER //Type in DevTools
- Number.MAX_VALUE //Type in DevTools
- Number.POSITIVE_INFINITY //Type in DevTools
Number("123") // 123 Number("12.3") // 12.3 Number("") // 0 Number("0x11") // 17 Number("0b11") // 3 Number("0o11") // 9 Number("foo") // NaN Number("100a") // NaN
parseInt() 函式能將輸入的字串轉成整數。
parseFloat() 函式能將輸入的字串轉成浮點數。
!!n 轉換為 Boolean
.toString()可以將所有的的資料都轉換為字串,但是要排除null 和 undefined
toString() 括號中的可以寫一個數字,代表進位制,對應進位制字串
二進位制:.toString(2);
八進位制:.toString(8);
十進位制:.toString(10);
十六進位制:.toString(16);
String()可以將null和undefined轉換為字串,但是沒法轉進位制字串
example:
var str = String(null);
console.log(str, typeof str);
var str = String(undefined);
console.log(str, typeof str);
運算子 | 例子 | 說明 |
---|---|---|
+ | x + y | x, y 相加 |
- | x - y | x,y 相減 |
* | x * y | x, y 相乘 |
/ | x /y | x,y 相除 |
% | x % y | x,y 取餘數 |
** | x **y | x 的 y 次方 |
& | x &y | x y 做位元 AND 運算 |
^ | x ^ y | x y 做位元 XOR 運算 |
| | x | y | x y 做位元 OR 運算 |
10 > 5 //true 10 是否大於 5
10 >= 5 //true
10 < 5 //false
10 <= 5 //false
10 == 5 //false 值是否相同
10 != 5 //true
10 === 5 //false 值是否相同, 型態也要相同
10 !== 5 //true 值是否不同, 嚴謹
////陣列
'a' in ['a','b'] //false
0 in ['a','b'] //true
//陣列是看索引位置的
var people = { firstName: 'Andy', lastName: 'Tseng', gender: 'M' };
'firstName' in people; //true
//邏輯 AND -> &&
let fruit = 'Apple' && 'Banana'
//邏輯 OR -> ||
let fruit = 'Apple' || 'Banana'
//邏輯 NOT -> !
let notTrue = !(true && true)
var str = 'This is string text';
var str = "This is string text";
var str = `This is string text` ;
可以使用 單引' 雙引" 與反引號` example:
這樣會發生錯誤 example:
var str = 'Andy's hat.';
var str = "This is a "cat".";
這樣可以解決 example:
var str = "Andy's hat."; // 雙引內放單引
var str = 'This is a "cat".'; // 單引內放雙引
用跳脫字元 (escape character) 反斜線 (backslash) \
來處理引號
example:
var str = 'Andy \'s hat.';
var str = "This is a \"cat\"."; // 單引內放雙引
跳脫字元 \ 還可以處理以下這些
特殊符號 | 表示的符號 |
---|---|
\0 | NULL 字元 |
' | 單引號 |
" | 雙引號 |
\ | 反斜線 |
\n | 換行符號 |
\r | return 回車鍵 |
\t | tab |
\v | vertical tab |
\b | backspace |
\f | form feed |
\uXXXX | unicode codepoint |
字串相加
let a = 'hel'+'llo'
//'hello'
let name = 'Andy'
//'Andy'
let greetings = a + ' ' + name
// 'hello Andy'
let greetings += '!'
//'hello Andy!'
多行字串
let a = 'hel' +
'llo ' +
'Andy' +
//'hello Andy'
//Or,
let a = 'hel \
llo \
Andy'
//'hello Andy'
let name = 'Andy'
let greetings = `Hello ${name}, How are you?`
// Length
console.log(greetings.length)
//split
console.log(greetings.split(""))
//(24) ["H", "e", "l", "l", "o", " ", "A", "n", "d", "y", ",", " ", "H", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u", "?"]
console.log(greetings.split(" "))
//(5) ["Hello", "Andy,", "How", "are", "you?"]
console.log(greetings.split(","))
//["Hello Andy", " How are you?"]
var str = "This is an 'ant'";
var index = str.indexOf("an");
console.log(index)
// 8
Get script tag
7-1: 使用ES3的方法
7-2: querySelector()
7-3: querySelectorAll()
document.querySelector('#my_id') // 抓單一物件 抓 id
document.querySelector('.my_class') // 抓第一物件 抓 class
document.querySelectorAll("p") // 抓所有的 p
document.querySelectorAll("a[target]")// 抓有target屬性的a
8-1: Case selector statement
8-2: Loop
8-3: break & continue
if(condition){
//When condition is true
}
if: Use "if" statement to run specific block of code when statement is true
if/else: when condition is true run block 1. When false, block 2
if( condition1){
//when condition is true to run
}else{
if(condition2{
}else{
if(condition3)
}
}
if(condition1){
//When condition is true to run
}else if(condition2){
}
else if(condition3){
}
switch(variable){
case value1:
//When the variable is the same as value1
break
case value2:
//When the variable is the same as value2
break
case value3:
//When the variable is the same as value3
break
default:
// default value
}
switch/case
switch/case
for(initial setup;condition;addition){
//block of code
}
// Example
for(i=0; i<8; i++){
console.log(i)
}
for loop
a++
means
a = a+1
which is adding 1 to the existing value
let i = 0
while(condition){
//Block of code
i++
}
// Example
let i = 0
while(i<5){
console.log(i)
i++
}
while Loop
let i = 0
do {
//block of code
i++
}while(condition)
// Example
let i = 0
do {
console.log(i)
i++
}while(i<5)
do while loop: Run for a time, then check condition
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.
9-1: What is Object?
9-2: Object Expression
9-3: for/in loop
var str = {firstName: 'Andy', lastName: 'Tseng'}
var list1 = ['apple', 'banana', 'cat']
str['firstName'] // Andy
str.firstName // Andy
delete str.firstName
Object: Objects are variables too. But objects can contain many values. It uses key and value in {}
Array: a dataset with order
Object: a key with a value and also called, hash table
key is a non-repeated "String", we also called it Dictionary
value can also be a function
key is without order
let obj = {}
let obj1 = Object()
for/in loop can be use with Object
and also Array
Object to get key
Array to get index
10-1: What is Array?
10-2: Array Expressions
10-3: Methods of Array
for/of use for iterable object, eg. Array,String
Differences:
let obj = {
a:'apple',
b:'banana',
c:'cake'
}
for(let key of Object.keys(obj)){
console.log(obj[key]);
}
// 不如直接 for in
for(let id in obj){
console.log(obj[id]);
}
var list1 = ['apple', 'banana', 'cat']
for(let i =0; i<list1.length;i++){
console.log(i+':'+ list1[i])
}
list1[2] = "cake"
Array is a combination of data with order. We use [] for expression. The index starts from 0
we use .length to know how long the array is
//Unicode way of sort
const slogan = 'Andy TV Pro Course'
const cutSlogan = slogan.split('')
cutSlogan.sort();
console.log(cutSlogan);
let follower = [ 6, 8, 10, 23, 8]
follower.sort()
console.log(follower);
// From small to large number
let follower = [ 6, 8, 10, 23, 8]
follower.sort(function(a,b){
return a-b
})
console.log(follower);
//Splice method
//.splice(index, number of delete items, Add items);
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
// forEach method
let man = [
{ name: 'Steve', age: 25, id: 'A006' },
{ name: 'Dave', age: 27, id: 'A009' },
{ name: 'Andy', age: 3, id: 'A088' },
];
man.forEach(function(val, index){
console.log( index +': ' + val.name )
})
// filter method
let words = ['spray', 'limit', 'elite', 'exuberant',
'destruction', 'present'];
let result = words.filter(function(word){return word.length > 6})
//let result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
// map method
let array1 = [1, 4, 9, 16];
// pass a function to map
let map1 = array1.map(function(x){ return x * 2});
console.log(map1);
// expected output: Array [2, 8, 18, 32]
// map method
let array1 = [1, 4, 9, 16];
// pass a function to map
let map1 = array1.map(function(x){ return x * 2});
console.log(map1);
// expected output: Array [2, 8, 18, 32]
let array1 = [1, 4, 9, 16];
let map1 = []
array1.forEach(function(x){
map1.push(x*2)
})
console.log(map1);
11-1: JSON string rules
11-2: Replication of Object and Array
11-3: Edit JSON Files
JSON is a text based data structure for storing and transmitting data. You can store various types of data, e.g, array, number, string and object. Also, complex syntax like object and array are allowed 。Once JSON is set, it's pretty easy to communicate and exchange data between applications since JSON is stored as plain text.
Advantage for using JSON:
{
"orderID": 54101,
"shopperName": "John Doe",
"shopperEmail": "johndoe@example.com",
"contents": [
{
"productID": 46,
"productName": "Helmet",
"quantity": 1
},
{
"productID": 98,
"productName": "Gas",
"quantity": 3
}
],
"orderCompleted": true
}
<object>
<property>
<key>orderID</key>
<number>54101</number>
</property>
<property>
<key>shopperName</key>
<string>John Doe</string>
</property>
<property>
<key>shopperEmail</key>
<string>johndoe@example.com</string>
</property>
<property>
<key>contents</key>
<array>
<object>
<property>
<key>productID</key>
<number>46</number>
</property>
<property>
<key>productName</key>
<string>Helmet</string>
</property>
<property>
<key>quantity</key>
<number>1</number>
</property>
</object>
<object>
<property>
<key>productID</key>
<number>88</number>
</property>
<property>
<key>productName</key>
<string>iPad</string>
</property>
<property>
<key>quantity</key>
<number>3</number>
</property>
</object>
</array>
</property>
<property>
<key>orderCompleted</key>
<boolean>true</boolean>
</property>
</object>
XML data size is larger than JSON
var jsonString = ' \
{ \
"orderID": 54101, \
"shopperName": "John Doe", \
"shopperEmail": "johndoe@example.com", \
"contents": [ \
{ \
"productID": 64, \
"productName": "Helmet", \
"quantity": 1 \
}, \
{ \
"productID": 88, \
"productName": "iPad", \
"quantity": 3 \
} \
], \
"orderCompleted": true \
} \
';
// JSON String to js Object
let cart = JSON.parse ( jsonString );
console.log( cart.shopperEmail );
console.log( cart.contents[1].productName );
// Turning JS Object to JSON String
let jsonStr = JSON.stringify(cart)
console.log(jsonStr)
let arrayA = [28, 77, 'abc', ['John', 63, 'male'] ];
let arrayB = arrayA;
let arrayC = arrayA.slice(); // Single layer
arrayA[3][0] = 'Mary';
arrayA[0] = 87;
console.log('arrayA:', arrayA);
console.log('arrayB:', arrayB);
console.log('arrayC:', arrayC);
Shallow copy,slice for deep copy
let arrayA = [28, 77, 'abc', ['John', 63, 'male'] ];
let arrayB = arrayA;
let arrayJSON = JSON.stringify(arrayA)
let arrayC = JSON.parse(arrayJSON)
arrayA[3][0] = 'Mary';
arrayA[0] = 87;
console.log('arrayA:', arrayA);
console.log('arrayB:', arrayB);
console.log('arrayC:', arrayC);
Let's try jsoneditoronline.org
12-1: Basic Function
12-2: Anonymous Function
12-3: Arrow Function
function functionName(params) {
// code in block
return returnValue
}
// Example
function myFunc() {
console.log('hi')
}
myFunc() // call myFunc function
Definition
// Use parameters
function myFunc(a, b) {
console.log('a:' + a)
console.log('b:' + b)
console.log('arguments:' + arguments)
console.log(JSON.stringify(arguments))
}
myFunc(5, 8, 7);
// ES6
function myFunc2(a, ...b) {
console.log('a:' + a)
console.log('b:' + b);
}
myFunc2(5, 8, 7);
//The old way
function multiplyJS(a, b) {
b = (typeof b !== 'undefined') ? b : 1;
return a * b;
}
multiplyJS(3, 3); // 9
multiplyJS(4, 6); // 24
multiplyJS(7); // 7
//ES6
function multiplyES6(a, b = 1) {
return a * b;
}
multiplyES6(3, 3); // 9
multiplyES6(4, 6); // 24
multiplyES6(7); // 7
var square = function(num) {
return num**2;
};
square(2) //4
square(3) //9
Use function directly without naming it
let square = (num) => {
return num**2;
}
let square = num => num**2
13-1: Global Scope
13-2: Local Scope
13-3: closure
Definition:
var a='apple'; //Global Variable
function banana(){
var b='banana'; //Local Variable
console.log('aInFunc:'+a)
console.log('bInFunc:'+b)
}
banana()
console.log('aNotInFunc:'+a)
console.log('aNotInFunc:'+b)
Closure allows the inside function run from outside
Take a look!Run function from inside out
14-1: Date object
14-2: setTimeout method
14-3: setInterval method
today = new Date() //No parameter -> Today
Xmas95 = new Date("December 25, 1995 13:30:00") //default as zero
Xmas95 = new Date(1995,11,25,9,30,0) //Multiple parameter
//"set" method: Setting the time value and Date
//"get" method: Getting the time value and Date
As we know learn how to use Date object.
Is there a way to program it?
Let's..GO!
function JSClock() {
//Save current time
let time = new Date()
//Get the hour from the time
let hour = time.getHours()
//Get the minute from the time
let minute = time.getMinutes()
//Get the second from the time
let second = time.getSeconds()
//Turn 0-24 to 0-12 am/pm
var temp = "" + ((hour > 12) ? hour - 12 : hour)
//if it's 0 then it's 12 o'clock
if (hour == 0)
temp = "12";
//If smaller than zero, you need to add zero to the minute
temp += ((minute < 10) ? ":0" : ":") + minute
//If smaller than zero, you need to add zero to the second
temp += ((second < 10) ? ":0" : ":") + second
//To recognize P.M and A.M
temp += (hour >= 12) ? " P.M." : " A.M."
return temp
}
Hold on a second
Can we run the code each second?
Yes we can!
Let's take a look!
// Syntax
setTimeout(function ,
milliseconds ,
param1 ,
param2 ,
...);
// Example
setTimeout(function(){
alert("Hello");
}, 3000);
Let's take a look!
setTimeout(function(){ console.log("2 seconds") }, 2000);
setTimeout(function(){ console.log("4 seconds") }, 4000);
setTimeout(function(){ console.log("6 seconds") }, 6000);
Multiple times?
// Syntax
setInterval(function,
milliseconds,
param1,
param2,
...);
// Example
let a = setInterval(function(){
console.log("Hello");
}, 3000);
//Clear Interval
setTimeout(function(){
clearInterval(a)
},20000)
15-1: Random Numbers
15-2: Trigonometric function
15-3: Circular placement
// 1. This function multiply the 0~0.999999 random value to 0~9.999999
// 2. Then, it floor it to 0-9 integer
// 3. Plus 1 to generate random integer from 1-10
Math.floor(Math.random() * 10) + 1;
// Math.floor Round down to integer
Math.random() Definition: Generates random number r, 0 ≤ r < 1
Math.floor()
Definition: Run down function, e.g., 5.8 -> 5
Example
function getRndInteger(min, max) {
return Math.floor(Math.random() *
(max - min) ) + min;
}
// Includes min Not max
.
function getRndInteger(min, max) {
return Math.floor(Math.random() *
(max - min + 1) ) + min;
}
// Includes min and max
.
// Use rad for angle.If you use 360 degrees, you need transformation.
// Math.PI * a degree / 180
Math.sin(3); // 0.1411200080598672
Math.sin(-3); // -0.1411200080598672
Math.sin(0); // 0
Math.sin(Math.PI); // 1.2246467991473532e-16
Math.sin(Math.PI / 2); // 1
// cos, tan also
.
.
16-1: Methods for window object
16-2: window properties
16-3: document properties
alert() // Alert window
blur() // blur out the window
clearInterval() // Clear the interval function
clearTimeout() // Clear the timeout function.
//Common forgotten
close() // Close window
confirm() // Confirm window
focus() // focus to the window
print() // Print the page for the printer
prompt() // Pop Prompt window
setInterval() // Trigger the function with interval
setTimeout() // Trigger the function after timeout
.
.
//Variable //Type // Information
URL // String // Webpage Address
anchors // HTMLCollection // Web Anchor
characterSet // String // Unicode Character Charset
cookie // String // Cookies
doctype // DocumentType // Doctype
domain // String // Readable Name Dor IP Address
forms // HTMLCollection // Collection for forms
head // HTMLHeadElement // Head Object
images // HTMLCollection // Collection for images
links // HTMLCollection // Connections To Other Page
referrer // String // Where it came from
title // String // Title For The Webpage
Document Common Example at 7-1-1
.
17-1: Event Handler
17-2: addEventListener
17-3: onclick vs. addEventListener
onclick // Trigger when single click
ondbclick // Trigger when double click
onmousedown // Trigger when mouse down
onmouseup // Trigger when mouse up
onmousemove // Trigger when mouse moves on top of the element
onmouseover // Trigger when mouse moves into the element
onmouseout // Trigger when mouse moves out of the element
onkeydown // Trigger when keypress down
onkeyup // Trigger when keypress up
onkeypress // Trigger when keypress (can be coninue)
onload // Trigger when element loads
onresize // Trigger when element resizes
onscroll // Trigger when element scrolls
onblur // Trigger when element move out of focus
onchange // Trigger when element value changes
// for input, select, textarea
onfocus // Trigger when element focus
onreset // Trigger when form reset
onselect // Trigger when element gets selected
// for input, textarea
onsubmit // Trigger when form is submitted
.
Syntax:
.
.
18-1: 什麼是 AJAX
18-2: XMLHttpRequest
18-3: fetch()方法
.
說明:
.
fetch API 讓 http 的處理更加簡單! 發送跟接收資料都可以!
.