这并不是对原始问题的直接字面回答,因为我更希望在数组中首先不要有重复的值。这是我的UniqueArray:
class UniqueArray extends Array {
constructor(...args) {
super(...new Set(args));
}
push(...args) {
for (const a of args) if (!this.includes(a)) super.push(a);
return this.length;
}
unshift(...args) {
for (const a of args.reverse()) if (!this.includes(a)) super.unshift(a);
return this.length;
}
concat(...args) {
var r = new UniqueArray(...this);
for (const a of args) r.push(...a);
return r;
}
}
> a = new UniqueArray(1,2,3,1,2,4,5,1)
UniqueArray(5) [ 1, 2, 3, 4, 5 ]
> a.push(1,4,6)
6
> a
UniqueArray(6) [ 1, 2, 3, 4, 5, 6 ]
> a.unshift(1)
6
> a
UniqueArray(6) [ 1, 2, 3, 4, 5, 6 ]
> a.unshift(0)
7
> a
UniqueArray(7) [
0, 1, 2, 3,
4, 5, 6
]
> a.concat(2,3,7)
UniqueArray(8) [
0, 1, 2, 3,
4, 5, 6, 7
]