JavaScript基础专题之类数组对象(七)
timelessover opened this issue · 0 comments
timelessover commented
类数组对象
简单概括:
拥有一个 length 属性和若干索引属性的对象
举个例子:
//数组
var array = ['name', 'age', 'sex'];
//类数组
var arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
Aarry.isAarry(arrLike) //false
两个对象都是可读写
、可获取长度
、遍历
读取
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++) {
……
}
但是他并不是真实的数组,所以并不能用数组原型上的方法。
比如:
arrayLike.push('4');// arrayLike.push is not a function
所以知识长得像数组。
一些应用
如果我们要调用数组上的方法怎么办呢?
别忘了我们可以用 Function.call 进行继承的方式,进行调用:
var arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
Array.prototype.join.call(arrayLike, '&'); // name&age&sex
Array.prototype.map.call(arrayLike, function(item){
return item.toUpperCase();
});
// ["NAME", "AGE", "SEX"]
类数组转数组
常用的奇技淫巧:
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)
Arguments对象
接下来说说 Arguments 对象。
Arguments 对象只定义在函数体中,包括了函数的参数和一些自身的属性。
举个例子:
function foo(name, age, sex) {
console.log(arguments);
}
foo('name', 'age', 'sex')
打印结果如下:
我们可以看到除了类数组的索引属性和length属性之外,还有一个 callee 属性,接下看看这些属性的定义。
length属性
length属性表示实参的长度,举个例子:
function foo(b, c, d){
console.log("实参的长度为:" + arguments.length)
}
console.log("形参的长度为:" + foo.length)
foo(1)
// 形参的长度为:3
// 实参的长度为:1
callee属性
callee 它可以调用函数自身。
讲个闭包经典面试题使用 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
接下来讲讲 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')
所以我们会发现形参会对应argument的索引,其实在传入形参过程中进行了一步我们隐式操作。
举个例子:
function foo(name) {
name = arguments[0]
}
以上是在非严格模式下,如果是在严格模式下,由于变量未声明的原因,实参和 arguments 是不会共享的。
继承参数
我们常用的继承:
//ES5
// 使用 apply 将 foo 的参数传递给 bar\
function bar(a, b, c) {
console.log(a, b, c);
}
function foo() {
bar.apply(this, arguments);//1,2,3
}
foo(1, 2, 3)
//ES6
class bar{
constructor(a,b,c){
this.a = a
this.b = b
this.c = c
}
}
class foo extends bar{
constructor(d){
super(...arguments)//继承参数a,b,c
this.d = d
}
}