123
209. Logical Operator
returns a Boolean value
==, === // 比較值 // 比較值&資料型態
!=, !== // 比較值 // 比較值&資料型態
>, <, >=, <=
console.log(3 === "3"); // type is different, but value is the same
console.log("3" === "3");
console.log(3 === 3);
console.log(4 != "4"); // values are different
console.log(4 !== "4"); // values and types are different
210. and, or Operator
Table…
211. if statement and condition
let age = prompt("How old are you?")
let ageInfo = "You are " + age + " years old. "
if (age <= 12)
alert(ageInfo + "Ticket price for children is NTD$150.");
else if (age > 65)
alert(ageInfo + "Ticket price for silver is NTD$100.");
else
alert(ageInfo + "Ticket price for adult age is NTD$250.");
212. System Improvement
上一節可能發生的問題,讓我們持續改進…
輸入檢查
輸入數字小於0
輸入數字大於150
輸入非數字
if (isNaN(age)) { // ■ 不能用 if (age == NaN)
alert("DON'T input strange words...")
}
資料型態轉換
-
number → string
number.toString() -
string → number
Number(string) // N大寫
213. Truthy and Falsy Values
-
false
-
0
-
“” (empty string)
-
null
-
undefined
-
NaN (Not a Number)
214. Naming Convention
Naming Convention 命名慣例
- camelCase
- underscore
- const with UPPERCASE
範例:
let youFoolish = 100;
let me_foolish = "100";
const PI = 3.14159265359;
215. Naming Restriction
Naming Restriction 命名限制
- starts with number:數字開頭
- hyphen in JS:減號
範例:
let 2youFoolish = 200; // ■ SyntaxError
// Uncaught SyntaxError: identifier starts immediately after numeric literal
// A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($).
// They can’t start with a digit! Only subsequent characters can be digits (0-9).
// JavaScript 變數必須以字母、下劃線 _ 或美元符號($)開頭。不能以數字開頭。
// 只有後續字符可以是數字(0-9)。
let 3-me-Foolish = “100100100”; // ■ SyntaxError
// Uncaught SyntaxError: unexpected token: ‘-’
- Array Properties
- Array Methods
◢ ■ ■ ■ ■ 火車車廂
│ │ │ │ │ │ │ │
═╡ ╞═╡ ╞═╡ ╞═╡ │
└───────┘ └───────┘ └───────┘ └───────┘
0 1 2 3
primitive 原始
comes in handy 實用
- is not a primitive data type.
- comes in handy when you need to store data together.
- index // 超出 index: undefined
- length
// 4 methods
- push()
- pop()
- shift()
- unshift()
建立陣列
var fruits = ['Apple', 'Banana'];
console.log(fruits.length);
// 2
(透過索引)取得陣列項目
var first = fruits[0];
// Apple
var last = fruits[fruits.length - 1];
// Banana
迭代陣列
fruits.forEach(function(item, index, array) {
console.log(item, index);
});
// Apple 0
// Banana 1
加入項目至陣列末端
var newLength = fruits.push('Orange');
// ["Apple", "Banana", "Orange"]
移除陣列末端項目
var last = fruits.pop(); // 移除 (最末端的) Orange
// ["Apple", "Banana"];
移除陣列前端項目
var first = fruits.shift(); // 移除 (最前端的) Apple
// ["Banana"];
加入項目至陣列前端
var newLength = fruits.unshift('Strawberry') // 加到陣列前端
// ["Strawberry", "Banana"];
在陣列中尋找項目的索引
fruits.push('Mango');
// ["Strawberry", "Banana", "Mango"]
var pos = fruits.indexOf('Banana');
// 1
移除指定索引位置的項目
var removedItem = fruits.splice(pos, 1); // 移除 pos 起的 1 個項目
// ["Strawberry", "Mango"]
移除指定索引位置起的多個項目
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
console.log(vegetables);
// ["Cabbage", "Turnip", "Radish", "Carrot"]
var pos = 1, n = 2;
var removedItems = vegetables.splice(pos, n);
// 這就是移除項目的方式,
// n 表示從該位置 (pos) 開始,一直到陣列的尾端有多少項目需要移除
console.log(vegetables);
// ["Cabbage", "Carrot"] (原始的陣列被改變)
console.log(removedItems);
// ["Turnip", "Radish"]
複製陣列
var shallowCopy = fruits.slice(); // 這就是複製陣列的方式
// ["Strawberry", "Mango"]
參考資料:
Array 所有的
// 4 methods
課外閱讀:
JS 常見陣列方法 [push(), unshift(), pop(), shift(), splice(), reverse(), concat(), include(), indexOf(), join()] _ 卡斯伯 Blog - 前端,沒有極限
■ 練習題:請將臉朝左的狗狗,改為臉朝右。
__ _
o'')}____//
`_/ )
(_(_/-(_/
圖形來源:ASCII Art Dogs - asciiart.eu
提示一:非左右對稱的 ASCII Code,要用相反的代替
提示二:字串長度不等的,要先填滿
■ 練習題:寫一個通用函數,來處理類似問題
(\_/)
( •_•)
/> OO>
218~220 Function
- Function Introduction
- function parameter
- return keyword
// function declaration
function sayHi() {
console.log("It's true then? What they're saying on the train.");
console.log("Harry Potter has come to Hogwarts.");
console.log("This is Crabbe and Goyle. And I'm Malfoy, Draco Malfoy.");
}
// invoke, execute a function
sayHi();
// ■ function parameter
function sayHi(yourName, myName) {
...
}
// invoke, execute a function
sayHi("Harry Potter", "Draco Malfoy");
// ■ Default parameters
function hello(name = 'Chris') {
console.log('Hello ${name}!');
}
hello('Ari'); // Hello Ari!
hello(); // Hello Chris!
// ■ Anonymous functions
(function () {
alert('hello');
})
// ■ Use case
// Normal function 一般寫法
function logKey(event) {
console.log('You pressed "${event.key}".');
}
textBox.addEventListener('keydown', logKey);
// Anonymous function 無名函數寫法
textBox.addEventListener('keydown', function(event) {
console.log('You pressed "${event.key}".');
});
// ■ Arrow functions:
// 呼叫 Anonymous function 的簡化寫法
// _______________ __________
// Instead of function(event), you write (event) =>
// 多行
textBox.addEventListener('keydown', (event) => {
console.log('You pressed "${event.key}".');
});
// 單行
textBox.addEventListener('keydown', (event) => console.log('You pressed "${event.key}".'));
// ■ return keyword
function squared(num) {
return num * num;
}
function cubed(num) {
return num * num * num;
}
function factorial(num) {
if (num < 0) return undefined;
if (num === 0) return 1;
let x = num - 1;
while (x > 1) {
num *= x;
x--;
}
return num;
}
參考資料:
Guides > JavaScript — Dynamic client-side scripting > JavaScript building blocks > Functions — reusable blocks of code
Functions versus methods
Function parameters
學習該如何開發 Web > JavaScript — 動態的客戶端指令 > JavaScript building blocks > 函數回傳值
Function 的四個測驗題:
- Quick Note
不見了
222~224 Object
- Object Property and Method
- this keyword
- Object and Array typeof
property
method
this
typeof
Object Property and Method
// Object Property and Method
let Wilson = {
// properties setting
first_name: "Wilson",
last_name: "Ren",
age: 30,
is_married: false,
spouse: null,
// methods setting
sayHi() {
console.log("Wilson says hi. ");
},
walk() {
console.log("Wilson is walking on the street. ");
},
say(word) {
console.log("Wilson says " + word);
}
};
// 兩種呼叫方式 [], dot notation
Wilson.sayHi();
Wilson.walk();
Wilson.say("today is a good day.");
this keyword
- “this” refers to the object that is calling the method.
- otherwise, it refers to the window object. (DOM)
// this keyword
...
sayAge() {
console.log("Wilson says I am "+ this.age + " years old. "); // this.age
}
Wilson.sayAge();
typeof
用 typeof 查詢上述的 Object 和 Array,發現輸出都是 Object
Array is a special type of object
// Object and Array typeof
...
console.log(Array)
// 輸出為 Object
225~229 for loop and while loop
- for loop and while loop syntax
- break and continue
- for loop syntax complement
- Nested Loop
- Loop through an Array
Syntax
let str225 = '';
for (let ii = 0; ii < 9; ii++) {
str225 = str225 + ii;
}
console.log(str225);
// expected output: "012345678"
While USE Case
不確定要執行幾次時
例:從1~100的數字中抽出一個數字,抽到7的時候就停止。
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
let result = '';
let i = 0;
do {
i = i + 1;
result = result + i;
} while (i < 5);
console.log(result);
// expected result: "12345"
參考資料:
for - JavaScript _ MDN
while - JavaScript _ MDN
do…while - JavaScript _ MDN
Keywords in Loop
- break
- continue
// 語法:break;
let i = 0;
while (i < 6) {
if (i === 3) {
break;
}
i = i + 1;
}
console.log(i);
// expected output: 3
// 語法:break label;
outerBlock: {
innerBlock: {
console.log('1');
break outerBlock; // breaks out of both inner_block and outer_block
console.log(':-('); // skipped
}
console.log('2'); // skipped
}
// 語法:continue;
let text = '';
for (let i = 0; i < 10; i++) {
if (i === 3) {
continue;
}
text = text + i;
}
console.log(text);
// expected output: "012456789"
// 語法:continue label;
let i = 0;
let j = 8;
checkiandj: while (i < 4) {
console.log(`i: ${i}`);
i += 1;
checkj: while (j > 4) {
console.log(`j: ${j}`);
j -= 1;
if ((j % 2) === 0)
continue checkj;
console.log(`${j} is odd.`);
}
console.log(`i = ${i}`);
console.log(`j = ${j}`);
}
// OUTPUT
i: 0
// start checkj
j: 8
7 is odd.
j: 7
j: 6
5 is odd.
j: 5
// end checkj
i = 1
j = 4
i: 1
i = 2
j = 4
i: 2
i = 3
j = 4
i: 3
i = 4
j = 4
參考資料:
break - JavaScript _ MDN
continue - JavaScript _ MDN
227. for loop syntax complement
主要講條件的變化
for (let i = 0; i < 9; i++) {
str = str + i;
}
228. Nested Loop
九九乘法表
228. Quick Note
When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller.
因此,在function當中的return keyword會停止整個function的運行,所有的for loop, while loop, if statement都會暫停。
例如:
function trying() {
for (let i = 0; i < 10; i++) {
console.log(i);
if (i == 5) {
return;
}
}
}
trying();
的結果是:
0
1
2
3
4
5
229. Loop through an Array
let friends = ["Josh", "John", "Mike"];
for (let i = 0; i < friends.length; i++) {
console.log(friends[i].toUpperCase());
}
230. Math Object
這些是 Math Object 中的 Static properties & Static methods,所以可以不用初始化,就能直接呼叫
提示:用 LATEX 數學式製作表格時,文字間的空白要用 \ ( 半型的\ + 空白鍵 spacebar)
上述程式碼示範:
231. Number Guessing Game
let max = 100;
let min = 0;
let temp = -1;
let answer = Math.trunc(Math.random() * (max - min) + min);
console.log(answer);
function game_data(max_number=100, min_number=0) {
temp = prompt("Please input a number between " + max_number + " and " + min_number + ": ");
// skip input checking: isNaN, max, min...
console.log(temp);
return temp;
}
let user_input = game_data(max, min);
// while (user_input != answer) {
for (i = 0; i < 8; i++) {
if (user_input > answer) {
max = user_input;
user_input = game_data(max, min);
} else if (user_input < answer) {
min = user_input;
user_input = game_data(max, min);
} else {
alert("GREAT! The correct answer is " + user_input);
break;
}
}
232. Reserved Words in JS
JavaScript 中的保留字,命名時請避開(強行命名會有 error)。
-
let
-
const
-
return
-
break
-
continue
-
…
233. Coding Exercise
使用 loop 將 array 倒過來。
Coding Exercise 1: Reverse An Array
const friends = ["Harry", "Ron", "Snap"];
const reversed_friends = [];
let len = friends.length;
for (let i=0; i < len; i++) {
reversed_friends.push(friends[len - 1 - i]);
}
console.log(reversed_friends);
Coding Exercise 2: Maximum Value of An Array
array 的 sort() 如果沒有加參數,會將 array 中的數字轉為 ASCII 排序。
所以比較大小時,要使用 compareFunction 的方式。
array.sort()
array.sort(compareFunction)
但他的 compareFunction 方式很特別,利用兩兩相減的數字大小來排序。
sort 方法可以直接使用 函式運算式(functions) 以及 閉包(closures):
// array.sort()
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
// array.sort(compareFunction)
var numbers = [1, 30, 4, 21, 100000];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// expected output: Array [1, 4, 21, 30, 100000]
function findBiggest(arr) {
if (arr.length == 0)
return "undefined";
arr.sort(function(a, b) {
return a - b;
});
// return biggestNumber;
return arr[arr.length - 1];
}
console.log(findBiggest([15, 20, 22, 16, 7])); // return 22
console.log(findBiggest([1, 2, 3, 4, 5, 999])); // return 999
console.log(findBiggest([-11, 0, -3, -4, -5, -999])); // return 0
console.log(findBiggest([])); // return undefined
參考資料:
Coding Exercise 3: Add Up to a Number
addUpTo(n) n為一個大於0的正整數。
撰寫 addUpTo() 使其 return 1 + 2 + 3 + … + n 的值。
function addUpTo(n) {
if (n <= 0)
alert("Please input an integer greater than 0.");
else {
let result = 0;
for (let i=0; i<=n; i++)
result += i;
return result;
}
}
console.log(addUpTo(5)); // 15
console.log(addUpTo(100)); // 5050
console.log(addUpTo(5000)); // 12502500
console.log(addUpTo(100000)); // 5000050000
- Coding Exercise 1 - Answer
- Coding Exercise 2 - Answer
- Coding Exercise 3 - Answer