我创建了这个数组,是我的版本,但对其进行了一些修改,与原始数组不同的是,在此数组中,您无法更改长度。
let ary = [1,2,3];
console.log(ary.length); //3
ary.length = 999;
console.log(ary.length); //999
因为我使用了get函数来获取我的长度,并使用闭包来保存原始数组长度的值。
let myArray = new MyArray(1,10); //new MyArray(from,to)
console.log(myArray.length); // 10
myArray.length = 999;
console.log(myArray.length); // 10 //still 10 because .length is a get function
我的数组代码是
let _getlength = {}, _inclength = {}, _declength = {};
class MyArray{
constructor(from, to)
{
this.key = Symbol('ignore this key');
[_getlength[this.key], _inclength[this.key], _declength[this.key]] = (
() =>
{
let length = 0;
let getLength = () =>
{
return length;
};
let inclength = () =>
{
length++;
this[length - 1] = 0;
return length;
};
let declength = () =>
{
return --length;
};
return [getLength, inclength, declength];
}
)();
if (from != null || to != null)
{
for (let num = from; num <= to; num++)
{
this.push(num);
}
}
}
push(value)
{
this[this.IncreaseLengthByOne() - 1] = value;
}
unshift(value)
{
this.addAt(0, value)
}
addAt(index, value)
{
this.IncreaseLengthByOne();
for (let i = this.length - 2; i >= index; i--)
{
this[i + 1] = this[i];
}
this[index] = value;
}
removeAt(index)
{
for (let i = index; i < this.length - 1; i++)
{
this[i] = this[i + 1];
}
this.pop();
}
pop()
{
_declength[this.key]();
delete this[this.length];
}
get length()
{
return _getlength[this.key]();
}
IncreaseLengthByOne()
{
return _inclength[this.key]();
}
forEach(callback)
{
for (let i = 0; i < this.length; i++)
{
callback(this[i], i, this);
}
}
map(callback)
{
let myArray = new MyArray();
for (let i = 0; i < this.length; i++)
{
myArray.push(callback(this[i], i, this));
}
return myArray;
}
* [Symbol.iterator]()
{
for (let i = 0; i < this.length; i++)
{
yield this[i];
}
}
}
示例:
创建一个名字数组,并向其中添加 "Ali"、"Hadi" 和 "Amber"
let names = new MyArray();
names.push('Ali');
names.push('Hadi');
names.push('Amber');
console.log(names);
将每个名字修改为在末尾添加他们的姓氏“Nawaz”,例如“Ali”变为“Ali Nawaz”
let fullNames = names.map(nam => nam +' Nawaz');
console.log(fullNames); //MyArray {0: "Ali Nawaz", 1: "Hadi Nawaz", 2: "Amber Nawaz"}