# 创建具有相同元素多次重复的数组

2020/09/30 22:41 · javascript ·  · 0评论

``````[2] * 5 # Outputs: [2,2,2,2,2]
``````

``````var repeatelem = function(elem, n){
// returns an array with element elem repeated n times.
var arr = [];

for (var i = 0; i <= n; i++) {
arr = arr.concat(elem);
};

return arr;
};
``````

``````function fillArray(value, len) {
if (len == 0) return [];
var a = [value];
while (a.length * 2 <= len) a = a.concat(a);
if (a.length < len) a = a.concat(a.slice(0, len - a.length));
return a;
}
``````

``````function fillArray(value, len) {
var arr = [];
for (var i = 0; i < len; i++) {
arr.push(value);
}
return arr;
}
``````

``````Array(5).fill(2)
//=> [2, 2, 2, 2, 2]
``````
``````>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> //Or in ES6
>>> [...Array(10)].map((_, i) => 5)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
``````

``````Array(6).join('a').split(''); // returns ['a','a','a','a','a'] (5 times)
``````

``````new Array(5).fill('a'); // give the same result as above;
// or
Array.from({ length: 5 }).fill('a')
``````

``````Array.apply(null, Array(3)).map(_ => 'abc') // ['abc', 'abc', 'abc']
``````

`Array.from({length:5}, i => 1) // [1, 1, 1, 1, 1]`

`Array.from({length:5}, (e, i)=>i) // [0, 1, 2, 3, 4]`

lodash中，还不错：

``````_.flatten(_.times(5, function () { return [2]; }));
// [2, 2, 2, 2, 2]
``````

``````_.times(5, _.constant(2));
// [2, 2, 2, 2, 2]
``````

``````_.fill(Array(5), 2);
``````

`[c] * n` 可以写成：

``````Array(n+1).join(1).split('').map(function(){return c;})
``````

``````Array(6).join(1).split('').map(function(){return 2;})
``````

``````Array.prototype.fill = function(val){
for (var i = 0; i < this.length; i++){
this[i] = val;
}
return this;
};
// used like:
var arry = new Array(5)​.fill(2);
// or
var arry = new Array(5);
arry.fill(2);

​console.log(arry);​ //[2, 2, 2, 2, 2]
``````

``````Array.from({length: 3}).fill(['a','b','c']).flat()
``````

``````Array(9) [ "a", "b", "c", "a", "b", "c", "a", "b", "c" ]
``````

``````> Array.from({length:5}).map(x => 2)
[ 2, 2, 2, 2, 2 ]
``````

``````var arrayA = ['a','b','c'];
var repeats = 3;
var arrayB = Array.apply(null, {length: repeats * arrayA.length})
.map(function(e,i){return arrayA[i % arrayA.length]});
// result: arrayB = ['a','b','c','a','b','c','a','b','c']
``````

``````function repeatElement(element, count) {
return Array(count).fill(element)
}
``````
``````>>> repeatElement('#', 5).join('')
"#####"
``````

``````const repeatElement = (element, count) =>
Array(count).fill(element)
``````
``````>>> repeatElement('#', 5).join('')
"#####"
``````

``````const repeatElement = element => count =>
Array(count).fill(element)
``````
``````>>> repeatElement('#')(5).join('')
"#####"
``````

``````const repeatElement = (element, count) =>
Array(count).fill(element)

>>> ['a', 'b', ...repeatElement('c', 5)]
['a', 'b', 'c', 'c', 'c', 'c', 'c']
``````

``````Array.prototype.map.call([]+Array(5+1),function(){ return '2'; })
``````

``````function fillArray(length, intValue) {
var vals = (new Array(length + 1)).join(intValue + '|').split('|').slice(0,length);
for(var i = 0; i < length; i += 1) {
vals[i] = parseInt(vals[i]);
}
return vals;
}
``````

``````fillArray(5, 7) // returns [7,7,7,7,7]
fillArray(5, 7.5) // returns [7,7,7,7,7]
fillArray(5, 200) // returns [200,200,200,200,200]
``````

``````var array = ['foo', 'bar', 'foobar'];
var filled = array.fill(7);

//filled should be ['foo', 'bar', 'foobar', 'foo', 'bar', 'foobar', 'foo']
``````

``````Array.prototype.fill = function(val){
var l = this.length;
if(l < val){
for(var i = val-1-l; i >= 0; i--){
this[i+l] = this[i % l];
}
}
return this;
};
``````

``````"#".repeat(5).split('').map(x => 0)
``````

“＃”字符可以是任何有效的单个字符。5将是所需元素数量的变量。7是您要用来填充数组的值。

http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/

``````"avinash ".repeat(5).trim().split(" ");
``````
``````var finalAry = [..."2".repeat(5).split("")].map(Number);
console.log(finalAry);``````

``````let result = _.map(_.times(foo), function() {return bar})
``````

``````function repeat(arr, len) {
while (arr.length < len) arr = arr.concat(arr.slice(0, len-arr.length));
return arr;
}
``````

``````function fillArray(value,len){
return [...Array(len).keys()].map(x=> value);
}
``````

``````fillArray(["Adam", "Blair", "Curtis"], 7); // returns ["Adam", "Blair", "Curtis", "Adam", "Blair", "Curtis", "Adam"]
``````

``````function fillArray(pattern, count) {
let result = [];
if (["number", "string"].includes(typeof pattern)) {
result = new Array(5);
result.fill(pattern);
}
else if (pattern instanceof Array) {
for (let i = 0; i < count; i++) {
result = result.concat(pattern);
}
result = result.slice(0, count);
}
return result;
}

fillArray("a", 5);        // ["a", "a", "a", "a", "a"]
fillArray(1, 5);          // [1, 1, 1, 1, 1]
fillArray(["a", "b"], 5); // ["a", "b", "a", "b", "a"]
``````