In Python, where [2]
is a list, the following code gives this output:
在Python中,其中[2]是一个列表,下面的代码给出了这个输出:
[2] * 5 # Outputs: [2,2,2,2,2]
Does there exist an easy way to do this with an array in JavaScript?
在JavaScript中是否存在一种简单的方法来处理数组?
I wrote the following function to do it, but is there something shorter or better?
我写了下面的函数来做它,但是有更短的或者更好的吗?
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;
};
18 个解决方案
#1
44
You can do it like this:
你可以这样做:
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;
}
It doubles the array in each iteration, so it can create a really large array with few iterations.
它在每次迭代中都将数组加倍,因此它可以创建一个具有很少迭代的非常大的数组。
Note: You can also improve your function a lot by using push
instead of concat
, as concat
will create a new array each iteration. Like this (shown just as an example of how you can work with arrays):
注意:您还可以通过使用push而不是concat来提高您的功能,因为concat将在每次迭代中创建一个新的数组。就像这样(演示了如何使用数组):
function fillArray(value, len) {
var arr = [];
for (var i = 0; i < len; i++) {
arr.push(value);
}
return arr;
}
#3
114
>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
#4
45
you can try:
你可以尝试:
Array(6).join('a').split(''); // returns ['a','a','a','a','a'] (5 times)
#5
26
In lodash it's not so bad:
在lodash中,它并没有那么糟糕:
_.flatten(_.times(5, function () { return [2]; }));
// [2, 2, 2, 2, 2]
EDIT: Even better:
编辑:更好:
_.times(5, _.constant(2));
// [2, 2, 2, 2, 2]
EDIT: Even better:
编辑:更好:
_.fill(Array(5), 2);
#6
21
Array.from({length:5}, i => 1) // [1, 1, 1, 1, 1]
from({length:5}, i => 1) // [1, 1, 1, 1, 1]
or create array with increasing value
或创建具有递增值的数组。
Array.from({length:5}, (e, i)=>i) // [0, 1, 2, 3, 4]
Array.from({长度:5 }、(e,i)= > i)/ /[0、1、2、3、4)
#7
14
[c] * n
can be written as:
[c] * n可以写成:
Array(n+1).join(1).split('').map(function(){return c;})
so for [2] * 5
对于[2]* 5。
Array(6).join(1).split('').map(function(){return 2;})
#8
11
You can also extend the functionality of Array like so:
还可以扩展数组的功能:
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]
I should note that extending the functionality of built-in objects can cause problems if you are working with 3rd-party libraries. Always weigh this into your decisions.
我应该注意到,如果您使用的是第三方库,那么扩展内置对象的功能会导致问题。总是在你的决定中权衡。
#9
3
No easier way. You need to make a loop and push elements into the array.
没有更简单的方法。您需要创建一个循环并将元素推入数组中。
#10
1
This function creates an array of (length) elements where each element equals (value) as long as (value) is an integer or string of an integer. Any decimal numbers will be truncated. If you do want decimal numbers, replace "parseInt(" with "parseFloat("
该函数创建一个数组(长度)元素,其中每个元素等于(值)只要(值)是整数或整数的字符串。任何十进制数都将被截断。如果您想要十进制数,请用“parseInt(”
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;
}
Examples:
例子:
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]
#11
1
I had problems with the mentioned methods when I use an array like
当我使用数组时,我遇到了上述方法的问题。
var array = ['foo', 'bar', 'foobar'];
var filled = array.fill(7);
//filled should be ['foo', 'bar', 'foobar', 'foo', 'bar', 'foobar', 'foo']
To get this I'm using:
为了得到这个,我用:
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;
};
#12
1
Another one-liner:
另一个一行程序:
Array.prototype.map.call([]+Array(5+1),function(){ return '2'; })
#13
1
In case you need to repeat an array several times:
如果您需要多次重复一个数组:
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']
inspired by this answer
灵感来自这个答案
#14
1
I discovered this today while trying to make a 2D array without using loops. In retrospect, joining a new array is neat; I tried mapping a new array, which doesn't work as map skips empty slots.
我今天发现了这一点,同时尝试在不使用循环的情况下创建一个2D数组。回想起来,加入一个新数组是很整洁的;我尝试映射一个新的数组,这个数组不工作,因为map跳过了空槽。
"#".repeat(5).split('').map(x => 0)
The "#" char can be any valid single character. The 5 would be a variable for the number of elements you want. The 7 would be the value you want to fill your array with.
“#”字符可以是任何有效的单个字符。5是你想要的元素个数的一个变量。7将是你想要填充数组的值。
The new fill method is better, and when I coded this I didn't know it existed, nor did I know repeat is es6; I'm going to write a blog post about using this trick in tandem with reduce to do cool things.
新的填充方法更好,当我编码的时候我不知道它的存在,我也不知道重复是es6;我将写一篇博客文章,关于使用这个技巧与减少做一些很酷的事情。
http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/
http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/
#15
0
If you are using a utlity belt like lodash/underscore you can do it like this :)
如果你使用的是像lodash/下划线这样的utlity带,你可以这样做:)
let result = _.map(_.times(foo), function() {return bar})
#16
0
Can be used as a one-liner too:
也可以作为一艘客轮使用:
function repeat(arr, len) {
while (arr.length < len) arr = arr.concat(arr.slice(0, len-arr.length));
return arr;
}
#17
0
Improving on Vivek's answer, this works for strings of any length, to populate an array of length n: Array(n+1).join('[string to be repeated][separator]').split('[separator]').slice(0, n)
改进Vivek的答案,这适用于任何长度的字符串,以填充长度为n:数组(n+1)的数组。加入(“[字符串重复][分离器]”).split(“[分离器]”)。片(0,n)
#18
0
Try This:
试试这个:
"avinash ".repeat(5).trim().split(" ");
#1
44
You can do it like this:
你可以这样做:
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;
}
It doubles the array in each iteration, so it can create a really large array with few iterations.
它在每次迭代中都将数组加倍,因此它可以创建一个具有很少迭代的非常大的数组。
Note: You can also improve your function a lot by using push
instead of concat
, as concat
will create a new array each iteration. Like this (shown just as an example of how you can work with arrays):
注意:您还可以通过使用push而不是concat来提高您的功能,因为concat将在每次迭代中创建一个新的数组。就像这样(演示了如何使用数组):
function fillArray(value, len) {
var arr = [];
for (var i = 0; i < len; i++) {
arr.push(value);
}
return arr;
}
#2
#3
114
>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
#4
45
you can try:
你可以尝试:
Array(6).join('a').split(''); // returns ['a','a','a','a','a'] (5 times)
#5
26
In lodash it's not so bad:
在lodash中,它并没有那么糟糕:
_.flatten(_.times(5, function () { return [2]; }));
// [2, 2, 2, 2, 2]
EDIT: Even better:
编辑:更好:
_.times(5, _.constant(2));
// [2, 2, 2, 2, 2]
EDIT: Even better:
编辑:更好:
_.fill(Array(5), 2);
#6
21
Array.from({length:5}, i => 1) // [1, 1, 1, 1, 1]
from({length:5}, i => 1) // [1, 1, 1, 1, 1]
or create array with increasing value
或创建具有递增值的数组。
Array.from({length:5}, (e, i)=>i) // [0, 1, 2, 3, 4]
Array.from({长度:5 }、(e,i)= > i)/ /[0、1、2、3、4)
#7
14
[c] * n
can be written as:
[c] * n可以写成:
Array(n+1).join(1).split('').map(function(){return c;})
so for [2] * 5
对于[2]* 5。
Array(6).join(1).split('').map(function(){return 2;})
#8
11
You can also extend the functionality of Array like so:
还可以扩展数组的功能:
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]
I should note that extending the functionality of built-in objects can cause problems if you are working with 3rd-party libraries. Always weigh this into your decisions.
我应该注意到,如果您使用的是第三方库,那么扩展内置对象的功能会导致问题。总是在你的决定中权衡。
#9
3
No easier way. You need to make a loop and push elements into the array.
没有更简单的方法。您需要创建一个循环并将元素推入数组中。
#10
1
This function creates an array of (length) elements where each element equals (value) as long as (value) is an integer or string of an integer. Any decimal numbers will be truncated. If you do want decimal numbers, replace "parseInt(" with "parseFloat("
该函数创建一个数组(长度)元素,其中每个元素等于(值)只要(值)是整数或整数的字符串。任何十进制数都将被截断。如果您想要十进制数,请用“parseInt(”
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;
}
Examples:
例子:
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]
#11
1
I had problems with the mentioned methods when I use an array like
当我使用数组时,我遇到了上述方法的问题。
var array = ['foo', 'bar', 'foobar'];
var filled = array.fill(7);
//filled should be ['foo', 'bar', 'foobar', 'foo', 'bar', 'foobar', 'foo']
To get this I'm using:
为了得到这个,我用:
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;
};
#12
1
Another one-liner:
另一个一行程序:
Array.prototype.map.call([]+Array(5+1),function(){ return '2'; })
#13
1
In case you need to repeat an array several times:
如果您需要多次重复一个数组:
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']
inspired by this answer
灵感来自这个答案
#14
1
I discovered this today while trying to make a 2D array without using loops. In retrospect, joining a new array is neat; I tried mapping a new array, which doesn't work as map skips empty slots.
我今天发现了这一点,同时尝试在不使用循环的情况下创建一个2D数组。回想起来,加入一个新数组是很整洁的;我尝试映射一个新的数组,这个数组不工作,因为map跳过了空槽。
"#".repeat(5).split('').map(x => 0)
The "#" char can be any valid single character. The 5 would be a variable for the number of elements you want. The 7 would be the value you want to fill your array with.
“#”字符可以是任何有效的单个字符。5是你想要的元素个数的一个变量。7将是你想要填充数组的值。
The new fill method is better, and when I coded this I didn't know it existed, nor did I know repeat is es6; I'm going to write a blog post about using this trick in tandem with reduce to do cool things.
新的填充方法更好,当我编码的时候我不知道它的存在,我也不知道重复是es6;我将写一篇博客文章,关于使用这个技巧与减少做一些很酷的事情。
http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/
http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/
#15
0
If you are using a utlity belt like lodash/underscore you can do it like this :)
如果你使用的是像lodash/下划线这样的utlity带,你可以这样做:)
let result = _.map(_.times(foo), function() {return bar})
#16
0
Can be used as a one-liner too:
也可以作为一艘客轮使用:
function repeat(arr, len) {
while (arr.length < len) arr = arr.concat(arr.slice(0, len-arr.length));
return arr;
}
#17
0
Improving on Vivek's answer, this works for strings of any length, to populate an array of length n: Array(n+1).join('[string to be repeated][separator]').split('[separator]').slice(0, n)
改进Vivek的答案,这适用于任何长度的字符串,以填充长度为n:数组(n+1)的数组。加入(“[字符串重复][分离器]”).split(“[分离器]”)。片(0,n)
#18
0
Try This:
试试这个:
"avinash ".repeat(5).trim().split(" ");