codecamp

Function return values

先决条件:

基本的计算机素养,对HTML和CSS的基本了解, JavaScript第一步函数 - 可重复使用的代码块

目的: 理解函数返回值,以及如何使用它们。

什么是返回值?

返回值就是它们的声音 - 当函数完成时返回的值。 你已经遇到了多次返回值,虽然你可能没有明确考虑它们。 让我们回到一些熟悉的代码:

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

我们在第一个函数文章中看到了这个代码块。 我们正在调用 replace()函数 > myText 字符串,并传递它两个参数 - 子字符串find和子字符串替换它。 当此函数完成(完成运行)时,它返回一个值,它是一个带有替换的新字符串。 在上面的代码中,我们将此返回值保存为 newString 变量的值。

如果您查看replace函数MDN参考页,您将看到一个名为 #Return_value">返回值 知道和理解函数返回的值是非常有用的,因此我们尽可能地包含这些信息。

一些函数不返回这样的返回值(在这些情况下,在我们的参考页中,返回值被列为 void undefined )。 例如,在 "> displayMessage()函数,我们在上一篇文章中创建,没有特定的值作为被调用的函数的结果返回。 它只是使一个框出现在屏幕上的某处 - 就是这样!

通常,使用返回值,其中函数是某种计算中的中间步骤。 你想得到一个最终结果,它涉及一些值。 这些值需要由函数计算,然后函数返回结果,以便它们可以在计算的下一阶段使用。

在自己的函数中使用返回值

要从自定义函数返回值,您需要使用...等待它... 语句/ return"> return 关键字。 我们最近在我们的 html"> random-canvas-circles.html 示例。 我们的 draw()函数在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();
  }
}

在每个循环迭代中,对 random()函数进行三次调用,以分别为当前圆的x坐标,y坐标和半径生成随机值。 random()函数接受一个参数 - 一个整数,它返回一个介于0和该数之间的整个随机数。 它看起来像这样:

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

这可以写成如下:

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

但第一个版本更快的写,更紧凑。

我们每次调用函数时返回计算结果 Math.floor(Math.random()* number) 此返回值出现在函数被调用的点处,代码继续。 例如,如果我们运行以下行:

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

并且三个 random()调用分别返回值500,200和35,则该行实际上将运行,就像这样:

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

在线路上的函数调用首先运行,它们的返回值代替函数调用,然后再执行线路本身。

主动学习:我们自己的返回值函数

让我们一起去写我们自己的函数,返回值。

  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) + '.';
      }
    }

    这里我们创建一个 onchange 事件处理程序,当change事件触发文本输入时运行 - 即在文本输入中输入一个新值并提交时(输入一个值,然后按Tab键 例如)。 当此匿名函数运行时,输入到输入中的现有值存储在 num 变量中。

    接下来,我们进行一个条件测试 - 如果输入的值不是一个数字,我们会在段落中打印一条错误消息。 该测试查看表达式 isNaN(num)是否返回true。 我们使用 isNaN()函数来测试num值是否为 不是数字 - 如果是,则返回 true ,如果不是,则返回 false

    如果测试返回 false ,则 num 值是一个数字,因此我们在段落元素中打印一个句子,说明数字的正方形, 句子调用 squared() cubed() factorial()函数来获取所需的值。

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

在这一点上,我们希望你在写出一些你自己的功能并将它们添加到库中的时候。 数字的方形或立方根,或半径为 num 的圆的圆周如何?

除了是如何使用 return 语句的研究,这个练习提出了几个重要的点。 此外,我们有:

  • 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.

结论

所以我们有它 - 函数是有趣的,非常有用的,虽然有很多谈论关于他们的语法和功能,给予正确的文章学习,可以理解。

如果您有任何不明白的地方,请随时阅读本文,或与我们联系以寻求帮助。

也可以看看

  • 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.

Build your own function
Introduction to events
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
CSS

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }