Javascript 主要是講互動,先講基礎的。
關於 coding,其實每個語言講的東西類似,但寫法不同,就像中文和英文一樣
程式的基礎:expression 與 statements
Statements,聲明。由很多個 Expression 表達式組成
x = y * 2; // 聲明
// 2, 數字的表達
// x, y 變數的表達
// y*2 算術的表達式
// = 是 assign 的表達式
// call expression
alert(x);
用開發者工具試玩 ( typora 竟然有 XD)
要測試的話,用 console.log()
比較好,不會干擾使用者
x = 32;
y = x*2;
console.log(y);
alert('hello')
input
好像只能在 chrome 開發者工具的側邊欄才能正常運作
name = prompt('what is your name?');
console.log('wowo, your name is' + name)
operators 運算元
除了剛剛提到的 expression 表達式外,程式裡還有 operators 運算元,是用來操作資料的運算符號。
常用的 - 1
// Assignment
x = 36;
// Math
x = x*6; // + - * /
// Compound assignment
x += 25; // += -= *= /=
// Increment / descrement
x++ // ++ --
常用的 - 2
// Object property access
console.log() // console 是物件,用 . 去存取屬性
// Equality
x == y // == !=
// Comparison
x <= 2 // < > <= >=
// Logical
x || y // && ||
值與它的型態
values & types
範例
"hello world";
87;
true;
false;
Comments 註解
// one line comment
/*
multiple
line
comment
*/
variables 變數
weak typing, dynamic typing, 弱型別
var age = 32;
age = "He is " + age + " years old.";
console.log(age);
block, conditions, loops
程式可以用來判斷條件來執行、重複數次
block
var iq = 87;
{
iq = iq * 2;
console.log(iq);
}
conditionals 條件判斷
var time = 10;
if (time > 18){
console.log('turn on the light');
}
else {
console.log('turn off the light');
}
loops 迴圈、迭代
var amountOfFood = 200;
while (amountOfFood > 0) {
// eat
amountOfFood --;
}
// 起始點、條件判斷、每次執行後會再運行這個部份
for (var i = 0; i<9; i++) {
console.log(i);
}
functions 請電腦幫你做的待辦清單
function 就是一串要做的事情的集合。把要做的事情記下來,再去 call 它,之後全部的事情都會做出來
function
function translateToPriceFormat(price) { // 形式參數 parameter
var price = price + '.00';
return price;
}
var priceFormat = translateToPriceFormat(500); // 實質參數 argument
console.log(priceFormat);
scope
var a = 1;
function doSomeMath() {
var a = 5;
console.log(a);
}
doSomeMath(); // 5,scope 是 doSomeMath() 裡面
console.log(a); // 1,scope 是最外層
如果把 doSomeMath() 裡的 a 拿掉
var a = 1;
function doSomeMath() {
console.log(a);
}
doSomeMath(); // 1,doSomeMath() 找不到 a,就往外層找
console.log(a); // 1
再把外層的 a 拿掉
function doSomeMath() {
var a = 5;
console.log(a);
}
doSomeMath(); // 5
console.log(a); // undefined,scope 只會往外找,找不到就回傳 undefined,沒有被定義過
object 與 array
object
property (index, key): value
var obj = {
hi: "hello world!",
price: 25;
isItGood: true,
cleanYourHouse: function() {
console.log('clean the house');
},
otherObj: {
foo: 'string a',
bar: 'string b',
},
};
console.log(obj.hi);
console.log(obj.price);
console.log(boj.isItGood);
obj.cleanYourHouse(); // call function
console.log(obj.otherObj.foo);
console.log(obj.otherObj.bar);
console.log(obj['hi']);
console.log(obj['price']);
console.log(obj['isItGood'])
array
var arraySample = [
"hello world!",
25
true,
];
console.log(arraySample[0]);
function as values
function foo() {
console.log('foo');
}
// function(){...} 是匿名函數
// 但因為有 assign 給變數,所以還是能呼叫
var bar = function() {
console.log('bar');
};
foo();
bar();
延伸,You Don't Know JS