arguments 是一个类数组对象。代表传给一个function的参数列表。

1.1 arguments length

arguments 是个类数组对象,其包含一个 length 属性,可以用 arguments.length 来获得传入函数的参数个数。

function func() {
console.log("The number of parameters is " + arguments.length);
} func();
func(1, 2);
func(1, 2, 3);

执行结果如下:

The number of parameters is 0
The number of parameters is 2
The number of parameters is 3

1.2 arguments 转数组

通常使用下面的方法来将 arguments 转换成数组:

Array.prototype.slice.call(arguments);
[].slice.call(arguments);

1.3 leaking arguments

另外,有一个需要注意的地方就是,不能将函数的 arguments 泄露或者传递出去。什么意思呢?看下面的几个泄露 arguments 的例子:

// Leaking arguments example1:
function getArgs() {
return arguments;
} // Leaking arguments example2:
function getArgs() {
const args = [].slice.call(arguments);
return args;
} // Leaking arguments example3:
function getArgs() {
const args = arguments;
return function() {
return args;
};
}

上面的做法就直接将函数的 arguments 对象泄露出去了,最终的结果就是 V8 引擎将会跳过优化,导致相当大的性能损失。

可以这样做:

function getArgs3 () {
const args = new Array(arguments.length)
for (let i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
return args;
}

1.4 修改arguments的值

   // 修改arguments的值
function foo(a) {
"use strict";
console.log(a, arguments[0]); // 1 1
a = 10;
console.log(a, arguments[0]); // 10 1
arguments[0] = 20;
console.log(a, arguments[0]); // 10 20
}
foo(1);
function bar(a) {
console.log('-----非严格模式下的值变化------')
console.log(a, arguments[0]); // 1 1
a = 10;
console.log(a, arguments[0]); // 10 10
arguments[0] = 20;
console.log(a, arguments[0]); // 20 20
}
bar(1);

从上面的两个例子中可以看出,在严格模式下,函数中的参数与 arguments 对象没有联系,修改一个值不会改变另一个值。而在非严格模式下,两个会互相影响。

最新文章

  1. 谈一谈SQL Server中的执行计划缓存(上)
  2. VB检测按键CTRL+C的次数
  3. PDF 补丁丁 0.5.0.2731 发布(增加去除页面表单和链接水印功能)
  4. android原生ExpandableListView
  5. 【Cocos2d-x 3.x】 调度器Scheduler类源码分析
  6. [综]聚类Clustering
  7. 进阶版css的点滴
  8. 基于Django的web开发
  9. Location对象、History对象
  10. phpcms v9二次开发笔记
  11. window和nodejs作用域区别(待续)
  12. openmpi+NFS+NIS搭建分布式计算集群
  13. [方法] ubuntu12.04开启root账户
  14. SVN的trunk、branch、tag(二)
  15. JavaScript 复制对象
  16. 【一天一道LeetCode】#76. Minimum Window Substring
  17. ILMerge在MSBuild与ILMerge在批处理文件中运行
  18. 如何成功打造一款中台(PaaS)产品
  19. php 怎么在foreach中循环数组的时候添加元素的属性
  20. 一文让你熟练掌握Linux的ncat(nc)命令

热门文章

  1. 面向对象编程思想(OOP)总结
  2. Spring Boot 文件下载
  3. leetcode 题型 数据结构 解法 分类总结
  4. Theorem、Proposition、Lemma和Corollary等的解释与区别
  5. PHP算法之无重复字符的最长子串
  6. Git 如何使用ssh上传或者同步/下载项目到github
  7. Git中.gitignore忽略规则
  8. 关于Async与Await的FAQ
  9. Seam科普
  10. SSL和TLS漏洞验证