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
>>: Day6 - 读 Concurrency is not Parallelism - Rob Pike (一)
目前我们已经做出台股加权指数的 K 线图,但目前进度的线图的 x 轴没有时间,所以当使用者看到这张图...
+++ title = "Day 13:vim 设定档" date = &quo...
Day34 Golang 操作CSV CVS 是以逗号,及换行\n分隔的资料格式, 从CSV的英文(...
首先我们要先了解你的资料库要存放什麽,然後在开始设计。但此篇先直接带大家直接操作熟悉流程,以便之後的...
今天接着来看看如何搞定架设的设定档吧! 步骤 7 建立网站 在先前开启EC2时,我们透过user d...