function 是物件的一種,查看 function 的資料型態時結果會顯示 object。
定義一個函式包含三個部份,依次為:
// 定義函式
function sayHi(){
console.log("Hi!");
}
// 呼叫函式
sayHi(); // Hi!
// 定義函式
function sayHi(name){
console.log("Hi!" + name);
}
// 呼叫函式
sayHi("Lily"); // Hi!Lily
function count(a, b){
console.log(a + b);
}
count(3,5); // 8
console.log(count(3,5)); // undefined
console.log(count(3, 5))
會出現 undefined 的結果,是因為在 function 裡面只是使用 console.log 把值印出來,並沒有用 return,所以沒有回傳值。
改善的方式如下:
function count(a, b){
return(a + b);
}
let add = count(3,5);
console.log(add); // 8
prompt()
, push()
...等let friends=["John","May","Mike"];
let returnWord = friends.push("Mary");
console.log(returnWord); // 4
push()
return 的東西是新的陣列長度,所以上面的程式碼回傳 4
補充:
function count(a, b){
console.log(a * b);
}
count(5) // NaN
這時候可以在括號中放入預設值避免這種情況發生
function count(a = 1, b = 3){
console.log(a * b);
}
count(5) // 15
// 因為只填了 1 個參數,第 2 個參數預設值為 3,所以結果為 5 * 3 = 15
count(3,6) // 18
(function sayHi(){
console.log("Hi")
})()
// Hi
如果要放參數的話直接在括號裡放入即可
(function sayHi(name){
console.log("Hi "+name)
})("Mary");
// Hi Mary
物件 (object) 是一個複合資料型態 (composite data type),用 {}
裝資料,物件包含屬性(property)和方法(methods),物件的屬性值如果是一個函式,我們稱它是物件的方法 (method)。
let obj = new Object();
let obj = {};
[]
.
(dot notation)例如:
//property
let Jay = {
name : "Jay",
age:30
};
console.log(Jay.age); // 30
console.log(Jay["age"]) // 30
//property
let Jay = {
name : "Jay",
age:30,
//method
walk(){
console.log("Jay is walking on the street.");
},
say(word){
console.log("Jay says " + word)
}
};
Jay.walk(); // Jay is walking on the street.
Jay.say("Hello!"); // Jay says Hello!
可以用 .
賦值,也可以用 [] 賦值
let home={};
home["motherName"] = "Mary";
home["fatherName"] = "John";
home.dogs = 1;
home.children = 3;
console.log(home) // {motherName:"Mary",fatherName:"John",dogs:1,children:3}
let home={
motherName:"Mary",
fatherName:"John",
dogs:1,
children:3
};
home.motherName = "Janet"; // 重新賦予值
home.dogs += 2; //也等於 home.dogs=home.dogs+2
console.log(home); // {motherName:"Janet",fatherName:"John",dogs:3,children:3}
let home={
motherName:"Mary",
fatherName:"John",
dogs:1,
children:3
};
delete home.dogs;
console.log(home) // {motherName:"Janet",fatherName:"John",children:3}
delete home.motherName;
console.log(home) // {fatherName:"John",children:3}
console.log(home.motherName) // undefined (已經刪除了找不到資料)
補充:
JavaScript 內建的物件有 Number, Math, Date, String, Array, RegExp...等,且每個都有自己的屬性與方法。
Math 和 Date 的詳細介紹在 Day 29 - Math object & Date object
參考資料:
MDN - 函式
JavaScript Object