arguments和类数组

arguments 是一个对应于传递给函数的参数的类数组对象。

什么是类数组呢?

类似于Array,但除了length属性和索引元素之外没有任何Array属性。但是类数组可以被转换为真正的数组。

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));

const args = Array.from(arguments);
const args = [...arguments];

arguments的使用

  • length属性表示实参的确切个数
  • 可以通过数组索引的方式获取单个参数的值
  • 作为函数参数的别名(非严格模式)
function assert(bol, cons) {
  if(bol) {
    console.log(cons)
  }
}

function whatever(a,b,c) {
  // 值的准确性校验
  assert(a === 1, 'the value of a is 1')
  assert(b === 2, 'the value of b is 2')
  assert(c === 3, 'the value of c is 3')

  // 共传入 5 个参数
  assert(arguments.length === 5, 'we have passed in 5 parameters')
  // 验证传入的前3个参数与函数的3个形参匹配
  assert(arguments[0] === a, 'the first argument is assigned to a')
  assert(arguments[1] === b, 'the second argument is assigned to b')
  assert(arguments[2] === c, 'the third argument is assigned to c')
  // 验证额外的参数可以通过参数 arguments 获取
  assert(arguments[3] === 4, 'can access the fourth argument')
  assert(arguments[4] === 5, 'can access the fifth argument')

  // 别名
  assert(a === 1, 'the a is 1')
  assert(arguments[0] === 1, 'the first argument is 1')

  arguments[0] = 666
  assert(a === 666, 'now, the a is 666')
  assert(arguments[0] === 666, 'now, the first argument is 666')

  a = 999
  assert(a === 999, 'now, the a is 999')
  assert(arguments[0] === 999, 'now, the first argument is 999')
}

whatever(1,2,3,4,5)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,681评论 0 4
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 10,165评论 0 5
  • JavaScript语言精粹 前言 约定:=> 表示参考相关文章或书籍; JS是JavaScript的缩写。 本书...
    微笑的AK47阅读 3,680评论 0 3
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 13,150评论 0 3
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 9,961评论 0 5

友情链接更多精彩内容