[Week 2] JavaScript - 函式 function


Posted by Mily on 2020-07-20

function 函數名稱(參數){
    要執行的代碼
}

範例:

function myFunction(p1, p2) {
    return p1 * p2;    // 回傳 p1 * p2
}

console.log(myFunction(3, 5))
=> 即得 15

function 也是個資料型態,所以也可以這麼做:

function hello() {
  console.log('hello')
}

-------------------------

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

以上兩種寫起來是差不多的,但還是有差別的

function 裡面也可以再包 function:

function print(anything) {
  anything() // 2. 會得到 hello() 這個 function
}

function hello(){
  console.log('hello') // 3. 最後結果
}

print(hello) // 1. 先看這行把 hello 傳進去 

=> 最後結果即得 hello

Return 的作用

  • 不需要知道結果
  • 需要知道運算完回傳了什麼東西

不需要知道結果

function sayHello(name){
  console.log('hello', name)
}

sayHello('Mily')
=> 即得 hello Mily

需要知道回傳值

function double(x) {
return x * 2
}

var result = doubel(3)
console.log(result)
=> 即得 6

數字相關函式

Number

var a = 10
var b = '20'
var c = '20.201234'

console.log(a + 以下提及的函式)

Number(b)

console.log(a + Number(b)):即會直接把字串轉成數字

parseInt(c, 多少進位)

console.log(a + parseInt(c, 多少進位):parseInt 印出來的值是整數(會去掉小數點),可以加上第二個參數,決定要多少進位,但也可以不寫

parseFloat()

console.log(a + parseFloat(c)):可以完成印出包含小數點的數字

console.log(parseFloat(c).toFixed(n))

搭配上面的提到的parseFloat() ,在後面加上 .toFixed(n),並把 N 替換成想要顯示幾個小數點後面的數字出來,也可以不寫,不寫即會去掉所有小數點

toString()

數字轉字串

var a = 2

第一種:
a.toString()
// 直接輸入就好,不需要 console.log

第二種:
(a + '')
// 數字 + 字串會變成字串

Math

Math.ceil(n)

無條件進位

Math.floor(n)

無條件捨去

Math.round(n)

四捨五入

Math.sqrt(n)

開根號

Math.pow(n 幾次方)

可以得到 n 的 __ 次方

Math.random()

得到隨機數字,範圍是 0<1


字串相關函式

toUppercase()

把字串都變成大寫

var a = 'abc'.toUppercase()
console.log(a)

=> 即得 ABC

toLowercase()

把字串都變成小寫

影片:String 類型的內建函式
有些沒寫出來


陣列相關函式

join('字元')

在陣列中間加入東西

var arr = [1, 2, 3]
console.log(arr.join('!'))

=> 即得 1!2!3

map(函式)

在陣列中間加入東西

var arr = [1, 2, 3]

functiion double(x){
  return x*2
}
console.log(arr.map(double))

=> 即得 [2, 4, 6]

---------------

或直接把函式寫在 console.log 裡面也可以

console.log(arr.map(functiion double(x){
  return x*2
}))

=> 一樣即得 [2, 4, 6]
後面可以再加入 map,再去看影片

(以上內容是我在 程式導師實驗計畫第四期 的學習紀錄,如有理解錯誤,歡迎糾正,謝謝:D)
資料來源:Lidemy


#javascript







Related Posts

如何在 Windows 安裝 OpenPose 跟使用 Python API 來偵測人體姿態

如何在 Windows 安裝 OpenPose 跟使用 Python API 來偵測人體姿態

SQL Add Column on existed Table

SQL Add Column on existed Table

1 認識元件

1 認識元件


Comments