JS 函数中的 arguments 类数组对象
1. arguments 介绍
2. arguments 转为数组
3. 箭头函数中没有 arguments
1. arguments 介绍
众所周知,js 是一门非常灵活的语言。当我们在 js 中调用一个函数时,经常会给函数传递一些参数,js 把调用函数时传入的全部实参存储到一个叫做 arguments 的类数组对象里面
arguments 是一个类数组对象,不是一个真正的数组。它类似数组,除了 length 属性和通过索引获取元素之外没有任何数组属性。这一点可以通过打印它看到
function test() { console.dir(arguments);}test('html', 'css', 'js')console.dir(['html', 'css', 'js'])
通过打印结果可以发现,arguments 的原型是 Object,而数组的原型是 Array
那么关于 arguments 是什么 ? 这里做下总结
arguments 是类数组对象(伪数组),即不是一个真正的数组,而是一个对象。它有 length 属性,并且可以通过下标获取元素,但是它不能调用数组方法,就是因为它不是真正的数组,这一点可以通过查看它的原型验证
2. arguments 转为数组
arguments 是类数组对象,不是一个真正的数组,意味着不能使用数组方法,但是可以将它转换为真正的数组
方法一: 直接遍历(新手写法)
const args = [];for (let i = 0; i < arguments.length; i++) { args.push(arguments[i])}
方法二: Array.prototype.slice(下面两种方式都可以)
const args = Array.prototype.slice.call(arguments)const args = [].slice.call(arguments)
方法三: ES6 语法(下面两种方式都可以)
const args = [...arguments]const args = Array.from(arguments)
3. 箭头函数中没有 arguments
arguments 只存在于普通函数中,而在箭头函数中是不存在的
下面代码抛出错误异常:Uncaught ReferenceError: arguments is not defined
const arrow = () => { console.log(arguments);}arrow('html', 'css', 'js')
箭头函数中虽然没有 arguments,但是可以使用 ...
接收所有实参
const arrow = (...args) => { console.log(args);}arrow('html', 'css', 'js')
本站发布的内容若侵犯到您的权益,请邮件联系站长删除,我们将及时处理!
从您进入本站开始,已表示您已同意接受本站【免责声明】中的一切条款!
本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行研究。
本站资源仅供学习和交流使用,版权归原作者所有,请勿商业运营、违法使用和传播!请在下载后24小时之内自觉删除。
若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,使用者自行承担,概与本站无关。