类数组对象
类数组对象: 就是拥有一个length属性和若干索引属性的对象1
2
3
4
5
6
7
8var array = ['name', 'age', 'sex']
var arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
读写
1 | console.log(array[0]); // name |
长度
1 | console.log(array.length); // 3 |
遍历
1 | for(var i = 0, len = array.length; i < len; i++) { |
那类数组对象可以使用数组的方法吗?比如:1
arrayLike.push('4');
然而上述代码会报错: arrayLike.push is not a function
调用数组方法
如果类数组就是任性的想用数组的方法怎么办呢?
既然无法直接调用,我们可以用 Function.call 间接调用:1
2
3
4
5
6
7
8
9
10
11var arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
Array.prototype.join.call(arrayLike, '&'); // name&age&sex
Array.prototype.slice.call(arrayLike, 0); // ["name", "age", "sex"]
// slice可以做到类数组转数组
Array.prototype.map.call(arrayLike, function(item){
return item.toUpperCase();
});
// ["NAME", "AGE", "SEX"]
类数组转数组
在上面的例子中已经提到了一种类数组转数组的方法,再补充三个:1
2
3
4
5
6
7
8
9var 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)