Array
const strings = ['a', 'b', 'c', 'd'];
strings[2] //O(1)
//push 数组末尾加,O(1),不循环,直接找到
strings.push('e')
//结果:(5) ['a', 'b', 'c', 'd', 'e']
//pop 删除末尾最后一个元素,O(1),不循环
strings.pop()
//结果:(4) ['a', 'b', 'c', 'd']
//unshift 数组开头添加元素,O(n),循环,数组原数据移动
strings.unshift('x')
//(5) ['x', 'a', 'b', 'c', 'd']
//splice 通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组 O(n)
strings.splice(2,0,'alien')
//结果:(5) ['a', 'b', 'alien', 'c', 'd']
strings.splice(2,1,'alien')
//结果:(4) ['a', 'b', 'alien', 'd']
console.log(strings)
手动创建一个数组类
class MyArray{
constructor(){
this.length = 0;
this.data = {}
}
get (index){
return this.data[index];
}
push(item){
this.data[this.length] = item;
this.length ++
return this.data;
}
pop(){
const lastItem = this.data[this.length -1];
delete this.data[this.length - 1];
this.length --;
return lastItem;
}
deleteAtIndex(index){
const item = this.data[index];
this.shiftItems(index);
return item;
}
shiftItems(index){
for(let i = index;i<this.length-1;i++){
this.data[i] = this.data[i+1];
}
delete this.data[this.length-1];
//console.log(this.data);
this.length--;
}
shift(){
const firstItem = this.data[0];
this.shiftItems(0);
return firstItem;
}
unshift(...funs){
}
}
const myArray = new MyArray();
myArray.push('I');
myArray.push('am');
myArray.push('are');
myArray.push('you');
console.log(myArray)
//myArray.deleteAtIndex(1)
myArray.shift();
console.log(myArray)