arguments的介绍(一)
2024-09-06 08:03:48
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 对象没有联系,修改一个值不会改变另一个值。而在非严格模式下,两个会互相影响。
最新文章
- 谈一谈SQL Server中的执行计划缓存(上)
- VB检测按键CTRL+C的次数
- PDF 补丁丁 0.5.0.2731 发布(增加去除页面表单和链接水印功能)
- android原生ExpandableListView
- 【Cocos2d-x 3.x】 调度器Scheduler类源码分析
- [综]聚类Clustering
- 进阶版css的点滴
- 基于Django的web开发
- Location对象、History对象
- phpcms v9二次开发笔记
- window和nodejs作用域区别(待续)
- openmpi+NFS+NIS搭建分布式计算集群
- [方法] ubuntu12.04开启root账户
- SVN的trunk、branch、tag(二)
- JavaScript 复制对象
- 【一天一道LeetCode】#76. Minimum Window Substring
- ILMerge在MSBuild与ILMerge在批处理文件中运行
- 如何成功打造一款中台(PaaS)产品
- php 怎么在foreach中循环数组的时候添加元素的属性
- 一文让你熟练掌握Linux的ncat(nc)命令