js中的Arguments对象
1.搞清楚什么是arguments
“arguments 是一个对应于传递给函数的参数的类数组对象。
arguments对象是所有(非箭头)函数中都可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。此对象包含传递给函数的每个参数,第一个参数在索引0处。”
首先它是一个类数组对象,typeof arguments结果毫无疑问是"object",注意结果是字符串类型。接下来调用Object.prototype.toString.call(arguments),结果是从未见过的"[object Arguments]"。
2.转换为数组
1.Array的silce方法
Array.prototype.slice.call(arguments)
2.Array.from
let re = Array.from(arguments)
3.拓展运算符
let re = [...arguments]3.从arguments到类数组
类数组必须有length属性,具有索引属性,下面结合代码说明:
let obj = {
"0": 'a',
"1": 'b',
"2": 'c',
length: 3,
"push": Array.prototype.push,
"splice": Array.prototype.splice
}
obj.push('d')
console.log(obj) 实际执行过程相当于:
obj[obj.length] = 'd';
obj.length++;
4.笔试题
var length = 10;
function fn(){
console.log(this.length)
}
var obj = {
length: 5,
getF: function(fn) {
fn();
arguments[0]();
}
}
obj.getF(fn);
考察的是arguments和this指向问题,我答的5 1,真实结果为10 1
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!