关于类数组的优点

先介绍下类数组,
首先看一个东西,arguments

function test() {
    console.log(arguments);
    arguments.a = 1;
    console.log(arguments.a);
}
test(1,2,3,4,5);//[1,2,3,4,5]

arguments打印出,看起来像一个数组,其实它不是,因为它没有数组的方法,像argument.push(1);这样写进去会报错的(arguments.push if not a function),这种属于其中一种类数组。

对象也可以是一种类数组

var obj = {
    "1" = "a",
    "2" = "b"
}
var arr = [a,b];

这样我们访问起来没啥大的区别,

var obj = {
    "0" : "a",
    "1" : "b",
    "2" : "c"
}
var arr = ["a","b","c"];
console.log(obj[1]);//b
console.log(arr[1]);//b

但我们知道数组是有length属性的,那么我们也给obj加上length属性。

var obj = {
    "0" : "a",
    "1" : "b",
    "2" : "c",
    "length" : 3
}
var arr = ["a","b","c"];
console.log(obj.length);//3
console.log(arr.length);//3

接下来为了我们的对象obj再像数组,我们加上Array原型链上的push方法。

var obj = {
    "0" : "a",
    "1" : "b",
    "2" : "c",
    "length" : 3,
    "push" : Array.prototype.push
}
var arr = ["a","b","c"];
obj.push("d");
arr.push("d");
console.log(obj);//多了"3" : "d"
console.log(arr);//["a","b","c","d"]
console.log(obj.length);//4
console.log(arr.length);//4

完美执行,但在console.log(obj);出来的还是对象的样子,所以我们得再加点东西,

var obj = {
    "0" : "a",
    "1" : "b",
    "2" : "c",
    "length" : 3,
    "push" : Array.prototype.push,
    "splice" : Array.prototype.splice
}
var arr = ["a","b","c"];
obj.push("d");
arr.push("d");
console.log(obj);//Object(4) ["a", "b", "c", "d", push: ƒ, splice: ƒ]
console.log(arr);//["a","b","c","d"]
console.log(obj.length);//4
console.log(arr.length);//4

虽然看起来相对数组还是多了点东西,但是已经不错了.最后总结几点,第一,属性要为索引(字符串数字)属性,必须有length属性,最好加上push和splice方法

然后我们再来看push的源码大意,

Array.prototype.push = function () {
    for(var i = 0; i < arguments.length; i++ ) {
        this.[this.length] = arguments[i];
        this.length ++;
    }
    return this.length;  
}

先仔细熟悉下上面的大意,以便我们进行下面的练习,

var obj = {
    "2" : "a",
    "3" : "b",
    "length" : 2,
    "push" : Array.prototype.push,
}
obj.push("c","d");
console.log(obj);//{2: "c", 3: "d", length: 4, push: ƒ}

从最上面我们说的arguments其实也是对象,是类数组,我们可以给arguments加属性

function test() {
    console.log(arguments);
    arguments.a = 1;
    console.log(arguments.a);
}
test(1,2,3,4,5);//控制台自行查看arguments.a

总结类数组的好处就是,它技能当对象用,也能当数组用,在一些场合(DOM)用处大。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。