类数组对象
拥有一个 length 属性和若干索引属性的对象,除了 arguments对象,一些 DOM 方法也会返回类数组对象。eg: document.getElementsByTagName()就会返回类数组对象
// 数组
var array = ['name', 'age', 'sex'];
// 类数组对象
var arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
<1> 类数组对象读写、长度、遍历等一些操作and属性和Array几乎一样
读写:
console.log(array[0]); // name
console.log(arrayLike[0]); // name
array[0] = 'new name';
arrayLike[0] = 'new name';
长度
console.log(array.length); // 3
console.log(arrayLike.length); // 3
遍历
for(var i = 0, len = array.length; i < len; i++) {
……
}
for(var i = 0, len = arrayLike.length; i < len; i++) {
……
}
<2> arguements 对象
arguments对象
只定义在函数体中(函数的一个属性),包括了函数的参数和其他属性。
function foo(name, age, sex) {
console.log(arguments);
}
foo('name', 'age', 'sex')
打印一下arguments对象
看看成分:
1) length 属性 表示实参的长度!!!
function foo(a,b,c){
console.log(arguments.length); // 1
console.log(foo.length); // 3 形参的长度
}
foo(a);
2) callee 属性 指向该函数本身
- 利用该属性可以实现函数的递归调用
- 可以解决闭包问题
var data = [];
for (var i = 0; i < 3; i++) {
(data[i] = function () {
console.log(arguments.callee.i)
}).i = i;
}
data[0]();
data[1]();
data[2]();
// 0
// 1
// 2
<3> arguments 和对应参数的绑定
记住两点:
非严格模式下:
- 传入了参数,实参和 arguments 的值会共享
- 没有传入参数时,实参与 arguments 值不会共享
严格模式下:
- 除此之外,以上是在非严格模式下,如果是在严格模式下,实参和 arguments 是不会共享的。
栗子:
function foo(name, age, sex, hobbit) {
console.log(name, arguments[0]); // name name
// 改变形参
name = 'new name';
console.log(name, arguments[0]); // new name new name
// 改变arguments
arguments[1] = 'new age';
console.log(age, arguments[1]); // new age new age
// 测试未传入的是否会绑定
console.log(sex); // undefined
sex = 'new sex';
console.log(sex, arguments[2]); // new sex undefined
arguments[3] = 'new hobbit';
console.log(hobbit, arguments[3]); // undefined new hobbit
}
foo('name', 'age')
<4> 调用数组的方法
那类数组能否使用数组的一些方法呢?
- 是可以的,但需要特殊形式的调用 ,比如用 .call() 方法去调用数组原型对象上的一些方法!!!
var arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
// 转字符串
Array.prototype.join.call(arrayLike, '&'); // name&age&sex
// slice可以做到类数组转数组,因为其返回结果是数组
Array.prototype.slice.call(arrayLike, 0); // ["name", "age", "sex"]
Array.prototype.map.call(arrayLike, function(item){
return item.toUpperCase();
});
// ["NAME", "AGE", "SEX"]
<5> 类数组对象转数组
- slice()
- splice()
- Array.from()
- concat
- [ ...arguments ]
var arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
// 1. slice
Array.prototype.slice.call(arrayLike); // ["name", "age", "sex"]
// 2. splice
Array.prototype.splice.call(arrayLike, 0); // ["name", "age", "sex"]
// 3. ES6 Array.from
Array.from(arrayLike); // ["name", "age", "sex"]
// 4. apply
Array.prototype.concat.apply([], arrayLike)
<6> arguments 对象的应用
- 参数不定长问题
- 函数柯里化
- 函数的递归调用(降低递归调用与函数名称之间的耦合性)
- 函数重载(函数参数的二次传递...)
// 使用 apply 将 foo 的参数传递给 bar
function foo() {
bar.apply(this, arguments);
}
function bar(a, b, c) {
console.log(a, b, c);
}
foo(1, 2, 3)