Function return values

2018-05-15 17:26 更新
先決條件:

基本的計算機素養(yǎng),對HTML和CSS的基本了解, JavaScript第一步,函數(shù) - 可重復(fù)使用的代碼塊 。

目的: 理解函數(shù)返回值,以及如何使用它們。

什么是返回值?

返回值就是它們的聲音 - 當(dāng)函數(shù)完成時返回的值。 你已經(jīng)遇到了多次返回值,雖然你可能沒有明確考慮它們。 讓我們回到一些熟悉的代碼:

var myText = 'I am a string';
var newString = myText.replace('string', 'sausage');
console.log(newString);
// the replace() string function takes a string,
// replaces one substring with another, and returns
// a new string with the replacement made

我們在第一個函數(shù)文章中看到了這個代碼塊。 我們正在調(diào)用 replace()函數(shù) > myText 字符串,并傳遞它兩個參數(shù) - 子字符串find和子字符串替換它。 當(dāng)此函數(shù)完成(完成運行)時,它返回一個值,它是一個帶有替換的新字符串。 在上面的代碼中,我們將此返回值保存為 newString 變量的值。

如果您查看replace函數(shù)MDN參考頁,您將看到一個名為 #Return_value">返回值。 知道和理解函數(shù)返回的值是非常有用的,因此我們盡可能地包含這些信息。

一些函數(shù)不返回這樣的返回值(在這些情況下,在我們的參考頁中,返回值被列為 void undefined )。 例如,在 "> displayMessage()函數(shù),我們在上一篇文章中創(chuàng)建,沒有特定的值作為被調(diào)用的函數(shù)的結(jié)果返回。 它只是使一個框出現(xiàn)在屏幕上的某處 - 就是這樣!

通常,使用返回值,其中函數(shù)是某種計算中的中間步驟。 你想得到一個最終結(jié)果,它涉及一些值。 這些值需要由函數(shù)計算,然后函數(shù)返回結(jié)果,以便它們可以在計算的下一階段使用。

在自己的函數(shù)中使用返回值

要從自定義函數(shù)返回值,您需要使用...等待它... 語句/ return"> return 關(guān)鍵字。 我們最近在我們的 html"> random-canvas-circles.html 示例。 我們的 draw()函數(shù)在HTML上在某處繪制100個隨機圓 < canvas> :

function draw() {
  ctx.clearRect(0,0,WIDTH,HEIGHT);
  for (var i = 0; i < 100; i++) {
    ctx.beginPath();
    ctx.fillStyle = 'rgba(255,0,0,0.5)';
    ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
    ctx.fill();
  }
}

在每個循環(huán)迭代中,對 random()函數(shù)進行三次調(diào)用,以分別為當(dāng)前圓的x坐標(biāo),y坐標(biāo)和半徑生成隨機值。 random()函數(shù)接受一個參數(shù) - 一個整數(shù),它返回一個介于0和該數(shù)之間的整個隨機數(shù)。 它看起來像這樣:

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

這可以寫成如下:

function random(number) {
  var result = Math.floor(Math.random()*number);
  return result;
}

但第一個版本更快的寫,更緊湊。

我們每次調(diào)用函數(shù)時返回計算結(jié)果 Math.floor(Math.random()* number)。 此返回值出現(xiàn)在函數(shù)被調(diào)用的點處,代碼繼續(xù)。 例如,如果我們運行以下行:

ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);

并且三個 random()調(diào)用分別返回值500,200和35,則該行實際上將運行,就像這樣:

ctx.arc(500, 200, 35, 0, 2 * Math.PI);

在線路上的函數(shù)調(diào)用首先運行,它們的返回值代替函數(shù)調(diào)用,然后再執(zhí)行線路本身。

主動學(xué)習(xí):我們自己的返回值函數(shù)

讓我們一起去寫我們自己的函數(shù),返回值。

  1. First of all, make a local copy of the function-library.html file from GitHub. This is a simple HTML page containing a text <input> field and a paragraph. There's also a <script> element in which we have stored a reference to both HTML elements in two variables. This little page will allow you to enter a number into the text box, and display different numbers related to it in the paragraph below.
  2. Let's add some useful functions to this <script> element. Below the existing two lines of JavaScript, add the following function definitions:
    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;
    }
    The squared() and cubed() functions are fairly obvious — they return the square or cube of the number given as a parameter. The factorial() function returns the factorial of the given number.
  3. Next we're going to include a way to print out information about the number entered into the text input. Enter the following event handler below the existing functions:
    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) + '.';
      }
    }

    這里我們創(chuàng)建一個 onchange 事件處理程序,當(dāng)change事件觸發(fā)文本輸入時運行 - 即在文本輸入中輸入一個新值并提交時(輸入一個值,然后按Tab鍵 例如)。 當(dāng)此匿名函數(shù)運行時,輸入到輸入中的現(xiàn)有值存儲在 num 變量中。

    接下來,我們進行一個條件測試 - 如果輸入的值不是一個數(shù)字,我們會在段落中打印一條錯誤消息。 該測試查看表達式 isNaN(num)是否返回true。 我們使用 isNaN()函數(shù)來測試num值是否為 不是數(shù)字 - 如果是,則返回 true ,如果不是,則返回 false 。

    如果測試返回 false ,則 num 值是一個數(shù)字,因此我們在段落元素中打印一個句子,說明數(shù)字的正方形, 。 句子調(diào)用 squared() cubed() factorial()函數(shù)來獲取所需的值。

  4. Save your code, load it in a browser, and try it out.

在這一點上,我們希望你在寫出一些你自己的功能并將它們添加到庫中的時候。 數(shù)字的方形或立方根,或半徑為 num 的圓的圓周如何?

除了是如何使用 return 語句的研究,這個練習(xí)提出了幾個重要的點。 此外,我們有:

  • Looked at another example of writing error handling into our functions. It is generally a good idea to check that any necessary parameters have been provided, and in the right datatype, and if they are optional, that some kind of default value is provided to allow for that. This way, your program will be less likely to throw errors.
  • Thought about the idea of creating a function library. As you go further into your programming career, you'll start to do the same kinds of things over and over again. It is a good idea to start keeping your own library of utility functions that you use very often — you can then copy them over to your new code, or even just apply it to any HTML pages where you need it.

結(jié)論

所以我們有它 - 函數(shù)是有趣的,非常有用的,雖然有很多談?wù)撽P(guān)于他們的語法和功能,給予正確的文章學(xué)習(xí),可以理解。

如果您有任何不明白的地方,請隨時閱讀本文,或與我們聯(lián)系以尋求幫助。

也可以看看

  • Functions in-depth — a detailed guide covering more advanced functions-related information.
  • Callback functions in JavaScript — a common JavaScript pattern is to pass a function into another function as an argument, which is then called inside the first function. This is a little beyond the scope of this course, but worth studying before too long.

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號