迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中函数的返回值

作者:迹忆客 最近更新:2024/03/17 浏览次数:

JavaScript 函数是执行这一系列步骤的基本构建块之一。这些功能就像过程。

执行任务的函数内部提供了一组指令。唯一的区别是该函数需要输入参数并且必须向调用者函数返回一些东西。要使用一个函数,你需要在你想调用它的范围内的某个地方定义它。

本文将展示如何从 JavaScript 函数返回值。


从 JavaScript 函数返回值

函数定义由 function 关键字组成。函数定义也称为函数语句或函数声明。紧随其后的是:

语法:

ES6 之前

function fnName(params) {
  /* perform actions on params */
  return value;
}

ES6 之后

param => expression

ES6 标准支持箭头函数,它不需要在定义函数之前定义函数关键字,返回值,并将代码括在大括号内。有关 ES6 函数的更多信息,请阅读 箭头函数 方法的文档。

该函数可以返回任何内容,例如数组、文字对象、字符串、整数、布尔值或你创建的封装返回值的自定义类型的对象。你可以将任何东西传递给函数,如数组、文字对象或自定义对象,以转换值的方法。

函数可以声明为表达式。该函数称为匿名函数。

匿名 函数没有任何函数名称。需要调用函数来执行函数内部的步骤。

有关更多信息,请阅读 Functions 方法的文档。

对象示例:

function osObject() {
  const returnedObject = {};
  for (let i = 0; i < arguments.length; ++i) {
    returnedObject['os' + i] = arguments[i];
  }
  return returnedObject;
}

const returnValue = osObject('Linux', 'MacOS', 'Windows', 'Ubuntu');
console.log(returnValue);

在上面的代码示例中,我们创建了函数 osObject,它接受输入参数并返回带有输入值的对象。return 关键字表示该函数正在向调用者返回一些东西。

在我们的示例中,我们将返回 osObject。上面代码的输出看起来像这样:

输出:

{
  os0: "Linux",
  os1: "MacOS",
  os2: "Windows",
  os3: "Ubuntu"
}

数组示例:

function osArray() {
  const returnedArray = [];
  for (let i = 0; i < arguments.length; ++i) {
    returnedArray.push(arguments[i]);
  }
  return returnedArray;
}

const returnValue = osArray('Linux', 'MacOS', 'Windows', 'Ubuntu');
console.log(returnValue);

在上面的代码示例中,我们创建了函数 osArray,它接受 arguments 中的输入参数并返回带有输入值的数组。return 关键字表示该函数正在向调用者返回一些东西。

在我们的示例中,我们将返回 osArray。上面代码的输出看起来像这样:

输出:

["Linux", "MacOS", "Windows", "Ubuntu"]

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便