重写基本函数(javascript)-数组

1.什么是数组
数组是线性数据结构,他用连续的内存空间来储存相同类型的数据
图1
array.png
图一就是一个典型的数组结构,第一行为数组的下标,第二列为数组的内容,第三列为数据的连续内存空间
2.重写javascript数据基本函数来加深印象
1.push(在数组的末尾增加一个新的对象)

`  /*
重写push
*/
Array.prototype.pushMunich = function (obj) {
    var data = this;
    var length = this.length;
    data[length] = obj;
    return data;
}

//测试
var array = [];
for(var i=0;i<100;i++){
    array.push(i+"push");
}
var push_begin_data=new Date().getTime();
array.push('zhangsan');
var push_end_data=new Date().getTime();
console.log("push:"+(push_end_data-push_begin_data)+"对象个数:"+array.length);

var pushMunich_begin_data=new Date().getTime();
array.pushMunich("zhangsan");
var pushMunich_end_data=new Date().getTime();
console.log("pushMunich:"+(pushMunich_end_data-pushMunich_begin_data)+"对象个数:"+array.length);`

我们在浏览器中执行上面的代码,结果图2
image.png
好的,我们回看这段测试代码,给数组的属性方法上增加了pushMunich的方法,参数为obj,当pushMunich被执行的时候,将obj赋值给当前长度的下标即array[101],由此可见,push的复杂度为O(1)

2.pop(将删除 arrayObject 的最后一个元素,把数组长度减 1,并且返回它删除的元素的值)

Array.prototype.popMunich = function () {
    var _length=this.length-1;
    var result=this[_length];
    this.length=_length;
    return result
}

//测试
var array = [];
for(var i=0;i<100;i++){
    array.push(i+"push");
}
var popMunich_begin_data=new Date().getTime();
var popMunich=array.popMunich();
var popMunich_end_data=new Date().getTime();
console.log(popMunich);
console.log("popMunich:"+(popMunich_end_data-popMunich_begin_data)+"对象个数:"+array.length);

var push_begin_data=new Date().getTime();
var pop=array.pop();
var push_end_data=new Date().getTime();
console.log(pop);
console.log("pop:"+(push_end_data-push_begin_data)+"对象个数:"+array.length);`

我们在浏览器中执行上面的代码,结果图3
image.png
好的,我们回看这段测试代码,给数组的属性方法上增加了popMunich的方法,当popMunich被执行的时候,直接返回最后一个元素,并且长度-1,由此可见,pop的复杂度为O(1)
注---这个代码只是实现了pop功能,至于有没有问题,欢迎指正
3.shift(用于把数组的第一个元素从其中删除,并返回第一个元素的值)

Array.prototype.shiftMunich = function () {
    var _length=this.length-1;
    var result=this[0];
    for(var i=0;i<_length;i++){
        var tem=this[i+1];
        this[i]=tem;
    }
    this.length=_length-1;
    return result
}
//测试
var array = [];
for(var i=0;i<100;i++){
    array.push(i+"push");
}

var shiftMunich_begin_data=new Date().getTime();
var shiftMunich=array.shiftMunich();
var shiftMunich_end_data=new Date().getTime();
console.log(shiftMunich);
console.log("shiftMunich:"+(shiftMunich_end_data-shiftMunich_begin_data)+"对象个数:"+array.length);

 var shift_begin_data=new Date().getTime();
var shift=array.shift();
var shift_end_data=new Date().getTime();
console.log(shift);
console.log("shift:"+(shift_end_data=new Date().getTime()-shift_begin_data)+"对象个数:"+array.length);

image.png



好的,我们回看这段测试代码,给数组的属性方法上增加了shiftMunich的方法,当shiftMunich被执行的时候,
1.返回下标为0的对象,
2.移动下标1的对象到下标0地址,以此类推
3.删除最后一个空对象
可得出结论:shiftMunich的复杂度为O(n)

由此可见,
1.数组在根据下标查询的速度是最快的,因为下标指向的是当前数据的内存地址
2.数组在末尾增加数据的时候,复杂度为O1,不需要重新排列
3.数组不在末尾增加或者删减数据的时候,是重新排列了数据,其复杂度为O(n),不建议使用
下周我因工作需要,会重写下Promise功能

评论

暂无评论