将 "arguments" 转变为 Array 的多种姿势
来源:互联网 发布:csoldjb9.0最终优化 编辑:程序博客网 时间:2024/06/11 17:39
在javascript中,arguments
对于 function
来说是一个非常重要的内定义数组,它拥有函数调用时所有传入的参数,这就是说我们可以在函数内遍历它来获取传入的所有参数,但是如果直接这样:
function Fun(){ arguments.forEach(function(value){ console.log(value); }); }; Fun(1,2,3,4,5,6,7,8,9,10);
运行时会报错
TypeError: arguments.forEach is not a function
使用typeof
来查看一下arguments
的类型:
console.log(typeof arguments);
运行得到如下结果
object
数组是特殊的对象,forEach()
是专为数组遍历的函数,所以我们要把arguments转变为Array
类型。
注意:以下均是在函数内部的语句
- 方法一
var args = Array.prototype.slice.call(arguments); args.forEach(function(value){});
- 方法二
var args = [].slice.call(arguments); args.forEach(function(value){});
- 方法三
var args = Array.from(arguments); args.forEach(function(value){});
- 方法四
var args = Array.apply(null,arguments); args.forEach(function(value){});
其实本意是要遍历arguments的,所以还有两种种不用转化为数组直接遍历的方案
- 方法一
for(var i=0; i<arguments.length; i++){}
- 方法二
for(key in arguments){ console.log(key); };
当然,你也可以选择这么写函数,只不过这是遵循最新的ES6标准
//ES6新方法 function Fun(...args){ args.forEach(function(value){}); };
0 0
- 将 "arguments" 转变为 Array 的多种姿势
- 将arguments属性转换成Array的几种方法
- 论RE的多种姿势
- javascript 将arguments 转化为array [].slice.apply(arguments)
- 文件上传检测的多种绕过姿势
- 文件上传检测的多种绕过姿势
- 将字符串转变为大小写
- Songreference:将你的mp3播放转变为video
- 将类转变为对象,取其中需要的值
- 将二元查找树转变为排序的双向链表
- 将字符串表示的IP地址转变为整形表示
- 如何将for iPhone的xib转变为for iPad
- 将一个进程转变为守护进程所需要的步骤
- swift-3.0 将HexColor转变为UIColor的方法
- Java8-如何将List转变为逗号分隔的字符串
- 将小写字母转变为对应的大写字母,反之亦然
- 十分钟认识单例模式的多种姿势
- Linux使用ps查看系统进程信息的多种姿势
- 加密算法介绍及加密算法的选择
- Python 播放声音 音频与beep
- C++ 新手新手上路第五天,数组的使用
- python 共享引用:多个变量引用同一对象
- mysql数据库时间类型data 和datatime区别
- 将 "arguments" 转变为 Array 的多种姿势
- VR行业解决方案
- throws如何用
- iOS中用swift转换日期的几个通用函数
- JAVA动态代理 和 Spring AOP 4种通知的简单实现
- Java 文件读写操作
- 各种排序算法思想总结
- libsvm最新源代码(版本3.21)理解解析(一)
- 寻找和为定值的N个数