第二周筆記 (JS) -3


Posted by RafealChen on 2021-04-30

基礎

函式 function

基本架構
f(x) = 2x+1

function 函數名稱(參數){
    return 程式
}

不同的宣告方式

function hello(){
    console.log('hello')
}
or
var hello = function(){
    console.log('hello')
}
--------------------------

function內可再使用其他function

function transform(x, transformFunction){
    return transformFunction(x)
}

function test(x){
    return x*2
}

console.log(
    transform(10,test)
)

anonymous funciotn 匿名函式
console.log(
    transform([1,2,3],function(x) {
        return x*3
        })
)

參數 parameter 引數 argument

function test(a, b){
    return a+b
}
test(4,5)
a, b 就是參數
4,5 就是引數
再Javascript
function test(a, b){
    console.log(argument) //可在function內打argument當作引數
    return a+b
}
這邊的argument會以object形式出現
argument.length可得知一共傳了幾個參數進來

使用function時的注意事項

再傳送引數進function時,一般的"數字", "字串", "布林值",直接以複製的形式傳送進function
並不會改變外面的值
但若是以object的形式,由於object是儲存記憶體位置,因此若function內的object指向與外面的object一樣,則會改變外面的值
pass by reference :在 JavaScript裡沒有
pass by value :
pass by sharing : 在 pass by sharing底下

深入探討 JavaScript 中的參數傳遞:call by value 還是 reference?

return

function分兩種
不需要知道結果:
function sayHello(name){
    console.log("Hello", name)
    return undefined (預設, 不影響結果)
}
需要知道結果:
function double {
    return x * 2
}
var result = double(3) 
console.log(result)

另外 在function裡使用return會立刻跳回去回傳值 接下來的指令並不會執行
function double {
    console.log(12345) //會執行
    return x * 2
    console.log(12345) //不會執行
}









Related Posts

Lidemy HTTP Challenge 破關紀錄

Lidemy HTTP Challenge 破關紀錄

Gomoku with React 用 React 做一個五子棋小遊戲

Gomoku with React 用 React 做一個五子棋小遊戲

AI輔導室|軟體自動完成算式

AI輔導室|軟體自動完成算式


Comments