1. 程式人生 > 實用技巧 >【JavaScript】函式返回值

【JavaScript】函式返回值

以下內容為學習記錄,可以參考 MDN 原文。

環境

  • vscode 1.46
  • Microsoft Edge 83

概念

返回值意如其名,是指函式執行完畢後返回的值。
有些函式沒有返回值就像(返回值在這種情況下被列出為空值 void 或未定義值 undefined)。

var newString = myText.replace('string', 'sausage');

返回值

function randomNumber(number) {
  return Math.floor(Math.random()*number);
}

示例

html 模板

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Function library example</title>
  <style>
    input {
      font-size: 2em;
      margin: 10px 1px 0;
    }
  </style>
</head>
<body>

  <input class="numberInput" type="text">
  <p></p>

  <script>
    const input = document.querySelector('.numberInput');
    const para = document.querySelector('p');

  </script>
</body>
</html>

定義函式

function squared(num) {
  return num * num;
}

function cubed(num) {
  return num * num * num;
}

function factorial(num) {
  var x = num;
  while (x > 1) {
    num *= x-1;
    x--;
  }
  return num;
}

定義事件

input.onchange = function() {
  var num = input.value;
  if (isNaN(num)) {
    para.textContent = 'You need to enter a number!';
  } else {
    para.textContent = num + ' squared is ' + squared(num) + '. ' +
                       num + ' cubed is ' + cubed(num) + '. ' +
                       num + ' factorial is ' + factorial(num) + '.';
  }
}