类数组

177 阅读1分钟

类数组

类数组就是定义了一个{} 空对象,里面添加length属性,push方法,splice方法

例1

function test(){
    console.log(arguments);
    // arguments.push(7);报错,不是数组
}
  test(1,2,3,4,5,6,7);

例2

var obj={
    "0":'a',//对象的属性可以是任何形式的
    "1":'b',
    "2":'c',
}
var arr = ['a','b','c'];

例1-06-08 151910.jpg

例3

var obj={
    "0":'a',
    "1":'b',
    "2":'c',
    "length":3,
    "push":Array.prototype.push,
    "splice":Array.prototype.splice
}

例3-06-08 152415.jpg

例3加上splice-06-08 152456.jpg

类数组:属性要为索引(数字)属性,必须有length属性,加上length可以进行一系列的处理。最好加上push方法 给对象加splice后长得和数组一样了,是对象,可以当数组用

push的时候关键点在length会覆盖push的东西

实现类数组

Array.prototype.push = function(target){
    obj[obj.length] = target;//this[this.length] = target;
    obj.length ++;
}

例4

var obj = {
    "2":"a",
    "3":"b",
    "length":2,
    "push":Array.prototype.push
}
obj.push('c');
obj.push("d");// push的时候关键点在length,会覆盖push的东西

例4-06-08 153932.jpg

变形

var obj = {
    "1":"a",
    "2":"c",
    "3":"d",
    "length":3,
    "push":Array.prototype.push
}
obj.push("b");

例4变形-06-08 154113.jpg

例5 遍历所有属性fot in循环

var obj = {
    "0":"a",
    "1":"b",
    "2":"c",
    name:"abc",
    age:123,
    length:3,
    push:Array.prototype.push,
    splice:Array.prototype.splice
}
for(var prop in obj) {//遍历所有属性fot in循环
    console.log(obj[prop]);
}

例5-06-08 154826.jpg