【发布时间】:2018-11-09 22:00:42
【问题描述】:
我有这个数组 [1,2,3]
我希望能够将其长度设置为 7
结果是 [1,2,3,1,2,3,1]。
有人吗?
const arr = [1,2,3];
// Something like
arr.resize(7);
console.log(arr); // [1,2,3,1,2,3,1]
编辑: 根据下面的 chevybow 答案,我编写了这个函数来满足我的需求。
// Immutable
Array.prototype.resize = function(size) {
const array = Array(size);
for(let i = 0; i < size; i++) {
array[i] = this[i%this.length];
}
return array;
}
// Mutable
Array.prototype.resize = function(size) {
const array = this.slice(0);
this.length = size;
for(let i = 0; i < size; i++) {
this[i] = array[i%array.length];
}
}
这些还好吗?或者你认为把它放在链上不是一个好主意,如果是这样,为什么?
【问题讨论】:
标签: javascript