其他分享
首页 > 其他分享> > 渡一 14-3 数组,类数组

渡一 14-3 数组,类数组

作者:互联网

类数组

function test(){
    console.log(arguments); //实参列表,并不是数组
    arguments.push(); //报错
}
test(1,3,3,4,5,6);
//特点:属性要为索引(数字)属性,必须有length属性,最好加上Push
obj = {
    "0" : "a",
    "1" : "b",
    "2" : "c",
    "length" : 3, //必须要加上的属性
    "push" : Array.prototype.push,
    "splice" : Array.prototype.splice //这条加上后就和数组长和一样了arr : ["a","b","c"];
}

obj.push("d") 

//结果
obj = {
    "0" : "a",
    "1" : "b",
    "2" : "c",
    "3" : "d",
}


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

 

阿里面视题

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

结果
obj {
    "2":"c",
    "3":"d",
    "length":4
}

/*2*/
obj {
    "1":"a",
    "2":"c",
    "3":"d",
    "length":3,
    "push" : Array.prototype.push
}

obj.push("b");

结果
obj {
    "1":"a",
    "2":"c",
    "3":"b",
    "length":4,
    "push" : Array.prototype.push
}

用法

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

 

练习

//封装type方法
typeof([])             --array
typeof({})             --object
typeof(function...)  --object
typeof(new Number)   --object number
typeof(123)            --number


//数组去重
//要求在原型链上编程
var arr=[1,1,3,3,5,5,"a","a"]
Array.prototype.unique = function(){
    //利用对象

}

 

 

 

标签:渡一,obj,14,--,length,数组,push,Array,prototype
来源: https://www.cnblogs.com/lisa2544/p/15328754.html