Is there a way in Javascript to write something like this easily:
在Javascript中是否有一种方法可以轻松编写这样的内容:
[1,2,3].times do {
something();
}
Any library that might support some similar syntax maybe?
有支持类似语法的库吗?
Update: to clarify - I would like something()
to be called 1,2 and 3 times respectively for each array element iteration
更新:为了澄清——我希望对每个数组元素迭代分别调用1、2和3次()
16 个解决方案
#1
19
This answer is based on Array.forEach
, without any library, just native vanilla.
这个答案基于数组。没有任何图书馆,只有本地的香草。
To basically call something()
3 times, use:
要基本调用某物()3次,使用:
[1,2,3].forEach(function(i) {
something();
});
considering the following function:
考虑下面的功能:
function something(){ console.log('something') }
The outpout will be
生产将会
something
something
something
To complete this questions, here's a way to do call something()
1, 2 and 3 times respectively:
为了完成这个问题,这里有一种方法可以分别调用1、2和3次:
It's 2017, you may use ES6:
[1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
something()
}))
or in good old ES5:
[1,2,3].forEach(function(i) {
Array(i).fill(i).forEach(function() {
something()
})
}))
In both cases, the outpout will be
在这两种情况下,输出都是
The outpout will be
生产将会
something
something
something
something
something
something
(once, then twice, then 3 times)
(1次,2次,3次)
#2
42
Just use a loop:
只使用一个循环:
var times = 10;
for(var i=0; i < times; i++){
doSomething();
}
#3
19
Possible ES6 alternative.
可能ES6选择。
Array.from(Array(3)).forEach((x, i) => {
something();
});
And, if you want it "to be called 1,2 and 3 times respectively".
如果你想让它被分别命名为1 2 3次。
Array.from(Array(3)).forEach((x, i) => {
Array.from(Array(i+1)).forEach((x, i2) => {
console.log(`Something ${ i } ${ i2 }`)
});
});
#4
18
Since you mention Underscore:
既然你提到强调:
Assuming f
is the function you want to call:
假设f是你想要调用的函数:
_.each([1,2,3], function (n) { _.times(n, f) });
will do the trick. For example, with f = function (x) { console.log(x); }
, you will get on your console: 0 0 1 0 1 2
上大做文章。例如,使用f = function (x) {console.log(x);},您将得到您的控制台:0 0 1 0 1 2。
#5
9
If you can't use Underscorejs, you can implement it yourself. By attaching new methods to the Number and String prototypes, you could do it like this (using ES6 arrow functions):
如果您不能使用Underscorejs,您可以自己实现它。通过向数字和字符串原型附加新方法,您可以这样做(使用ES6箭头函数):
// With String
"5".times( (i) => console.log("number "+i) );
// With number variable
var five = 5;
five.times( (i) => console.log("number "+i) );
// With number literal (parentheses required)
(5).times( (i) => console.log("number "+i) );
You simply have to create a function expression (of whatever name) and assign it to whatever property name (on the prototypes) you would like to access it as:
您只需创建一个函数表达式(无论名称),并将其分配给您希望以以下方式访问的任何属性名称(在原型上):
var timesFunction = function(callback) {
if (typeof callback !== "function" ) {
throw new TypeError("Callback is not a function");
} else if( isNaN(parseInt(Number(this.valueOf()))) ) {
throw new TypeError("Object is not a valid number");
}
for (var i = 0; i < Number(this.valueOf()); i++) {
callback(i);
}
};
String.prototype.times = timesFunction;
Number.prototype.times = timesFunction;
#6
8
We can use lodash to do this work by:
我们可以用lodash来做这个工作:
_.each([1, 2, 3], function(item) {
doSomeThing(item);
});
//Or:
_.each([1, 2, 3], doSomeThing);
Or if you want to do something N times:
或者如果你想做某事N次:
var n = 10;
_.times(n, function() {
doSomeThing();
});
//Or:
_.times(n, doSomeThing);
Reference this link for lodash
installation
引用此链接进行lodash安装
#7
2
// calls doSomething 42 times
Array( 42 ).join( "x" ).split( "" ).forEach( doSomething );
and
和
// creates 42 somethings
var somethings = Array( 42 ).join( "x" ).split( "" ).map( () => buildSomething(); );
or ( via https://*.com/a/20066663/275501 )
或者(通过https://*.com/a/20066663/275501)
Array.apply(null, {length: 42}).forEach( doSomething );
#8
2
var times = [1,2,3];
for(var i = 0; i < times.length; i++) {
for(var j = 0; j < times[i];j++) {
// do something
}
}
Using jQuery .each()
使用jQuery . each()
$([1,2,3]).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
OR
或
var x = [1,2,3];
$(x).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
EDIT
You can do like below with pure JS:
你可以用纯JS来做如下:
var times = [1,2,3];
times.forEach(function(i) {
// do something
});
#9
2
You can use a combination of underscore/lodash range
with forEach
您可以使用下划线/lodash range与forEach组合
_.range(10).forEach(myFunc) // call myFunc 10 times
1 .range(10).forEach(myFunc) //调用myFunc 10次。
#10
1
You can use length of array to execute number of times your task.
可以使用数组长度执行任务的次数。
var arr = [1,2,3];
for(var i=0; i < arr.length; i++){
doSomething();
}
or
或
var arr = [1,2,3];
do
{
}
while (i++ < arr.length);
#11
1
you can use
您可以使用
Array.forEach
Array.forEach
example:
例子:
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements)
or with jQuery
与jQuery或
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
http://api.jquery.com/jQuery.each/
http://api.jquery.com/jQuery.each/
#12
1
times = function () {
var length = arguments.length;
for (var i = 0; i < length ; i++) {
for (var j = 0; j < arguments[i]; j++) {
dosomthing();
}
}
}
You can call it like this:
你可以这样称呼它:
times(3,4);
times(1,2,3,4);
times(1,3,5,7,9);
#13
1
These answers are all good and well and IMO @Andreas is the best, but many times in JS we have to do things asynchronously, in that case, async has you covered:
这些答案都很好,IMO @Andreas是最好的,但是在JS中,很多时候我们需要异步处理,在这种情况下,async已经包括了:
http://caolan.github.io/async/docs.html#times
http://caolan.github.io/async/docs.html *
const async = require('async');
async.times(5, function(n, next) {
createUser(n, function(err, user) {
next(err, user);
});
}, function(err, users) {
// we should now have 5 users
});
These 'times' features arent very useful for most application code, but should be useful for testing.
这些“times”特性对于大多数应用程序代码并不是很有用,但是对于测试应该是有用的。
#14
0
Just use a nested loop (maybe enclosed in a function)
只需使用嵌套循环(可能包含在函数中)
function times( fct, times ) {
for( var i=0; i<times.length; ++i ) {
for( var j=0; j<times[i]; ++j ) {
fct();
}
}
}
Then just call it like this:
然后这样称呼它:
times( doSomething, [1,2,3] );
#15
0
const loop (fn, times) => {
if (!times) { return }
fn()
loop(fn, times - 1)
}
loop(something, 3)
#16
0
Given a function something
:
给定一个函数有:
function something() { console.log("did something") }
And a new method times
added to the Array
prototype:
在阵列原型中增加了一种新的方法时间:
Array.prototype.times = function(f){
for(v of this)
for(var _ of Array(v))
f();
}
This code:
这段代码:
[1,2,3].times(something)
Outputs this:
输出:
did something
did something
did something
did something
did something
did something
Which I think answers your updated question (5 years later) but I wonder how useful it is to have this work on an array? Wouldn't the effect be the same as calling [6].times(something)
, which in turn could be written as:
我想这能回答你更新后的问题(5年后),但是我想知道在数组上做这项工作有多有用?它的效果不是和调用[6].times(某物)一样吗?
for(_ of Array(6)) something();
(although the use of _
as a junk variable will probably clobber lodash or underscore if you're using it)
(虽然将_作为垃圾变量使用,如果您使用它,很可能会造成大量的破折号或下划线)
#1
19
This answer is based on Array.forEach
, without any library, just native vanilla.
这个答案基于数组。没有任何图书馆,只有本地的香草。
To basically call something()
3 times, use:
要基本调用某物()3次,使用:
[1,2,3].forEach(function(i) {
something();
});
considering the following function:
考虑下面的功能:
function something(){ console.log('something') }
The outpout will be
生产将会
something
something
something
To complete this questions, here's a way to do call something()
1, 2 and 3 times respectively:
为了完成这个问题,这里有一种方法可以分别调用1、2和3次:
It's 2017, you may use ES6:
[1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
something()
}))
or in good old ES5:
[1,2,3].forEach(function(i) {
Array(i).fill(i).forEach(function() {
something()
})
}))
In both cases, the outpout will be
在这两种情况下,输出都是
The outpout will be
生产将会
something
something
something
something
something
something
(once, then twice, then 3 times)
(1次,2次,3次)
#2
42
Just use a loop:
只使用一个循环:
var times = 10;
for(var i=0; i < times; i++){
doSomething();
}
#3
19
Possible ES6 alternative.
可能ES6选择。
Array.from(Array(3)).forEach((x, i) => {
something();
});
And, if you want it "to be called 1,2 and 3 times respectively".
如果你想让它被分别命名为1 2 3次。
Array.from(Array(3)).forEach((x, i) => {
Array.from(Array(i+1)).forEach((x, i2) => {
console.log(`Something ${ i } ${ i2 }`)
});
});
#4
18
Since you mention Underscore:
既然你提到强调:
Assuming f
is the function you want to call:
假设f是你想要调用的函数:
_.each([1,2,3], function (n) { _.times(n, f) });
will do the trick. For example, with f = function (x) { console.log(x); }
, you will get on your console: 0 0 1 0 1 2
上大做文章。例如,使用f = function (x) {console.log(x);},您将得到您的控制台:0 0 1 0 1 2。
#5
9
If you can't use Underscorejs, you can implement it yourself. By attaching new methods to the Number and String prototypes, you could do it like this (using ES6 arrow functions):
如果您不能使用Underscorejs,您可以自己实现它。通过向数字和字符串原型附加新方法,您可以这样做(使用ES6箭头函数):
// With String
"5".times( (i) => console.log("number "+i) );
// With number variable
var five = 5;
five.times( (i) => console.log("number "+i) );
// With number literal (parentheses required)
(5).times( (i) => console.log("number "+i) );
You simply have to create a function expression (of whatever name) and assign it to whatever property name (on the prototypes) you would like to access it as:
您只需创建一个函数表达式(无论名称),并将其分配给您希望以以下方式访问的任何属性名称(在原型上):
var timesFunction = function(callback) {
if (typeof callback !== "function" ) {
throw new TypeError("Callback is not a function");
} else if( isNaN(parseInt(Number(this.valueOf()))) ) {
throw new TypeError("Object is not a valid number");
}
for (var i = 0; i < Number(this.valueOf()); i++) {
callback(i);
}
};
String.prototype.times = timesFunction;
Number.prototype.times = timesFunction;
#6
8
We can use lodash to do this work by:
我们可以用lodash来做这个工作:
_.each([1, 2, 3], function(item) {
doSomeThing(item);
});
//Or:
_.each([1, 2, 3], doSomeThing);
Or if you want to do something N times:
或者如果你想做某事N次:
var n = 10;
_.times(n, function() {
doSomeThing();
});
//Or:
_.times(n, doSomeThing);
Reference this link for lodash
installation
引用此链接进行lodash安装
#7
2
// calls doSomething 42 times
Array( 42 ).join( "x" ).split( "" ).forEach( doSomething );
and
和
// creates 42 somethings
var somethings = Array( 42 ).join( "x" ).split( "" ).map( () => buildSomething(); );
or ( via https://*.com/a/20066663/275501 )
或者(通过https://*.com/a/20066663/275501)
Array.apply(null, {length: 42}).forEach( doSomething );
#8
2
var times = [1,2,3];
for(var i = 0; i < times.length; i++) {
for(var j = 0; j < times[i];j++) {
// do something
}
}
Using jQuery .each()
使用jQuery . each()
$([1,2,3]).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
OR
或
var x = [1,2,3];
$(x).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
EDIT
You can do like below with pure JS:
你可以用纯JS来做如下:
var times = [1,2,3];
times.forEach(function(i) {
// do something
});
#9
2
You can use a combination of underscore/lodash range
with forEach
您可以使用下划线/lodash range与forEach组合
_.range(10).forEach(myFunc) // call myFunc 10 times
1 .range(10).forEach(myFunc) //调用myFunc 10次。
#10
1
You can use length of array to execute number of times your task.
可以使用数组长度执行任务的次数。
var arr = [1,2,3];
for(var i=0; i < arr.length; i++){
doSomething();
}
or
或
var arr = [1,2,3];
do
{
}
while (i++ < arr.length);
#11
1
you can use
您可以使用
Array.forEach
Array.forEach
example:
例子:
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements)
or with jQuery
与jQuery或
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
http://api.jquery.com/jQuery.each/
http://api.jquery.com/jQuery.each/
#12
1
times = function () {
var length = arguments.length;
for (var i = 0; i < length ; i++) {
for (var j = 0; j < arguments[i]; j++) {
dosomthing();
}
}
}
You can call it like this:
你可以这样称呼它:
times(3,4);
times(1,2,3,4);
times(1,3,5,7,9);
#13
1
These answers are all good and well and IMO @Andreas is the best, but many times in JS we have to do things asynchronously, in that case, async has you covered:
这些答案都很好,IMO @Andreas是最好的,但是在JS中,很多时候我们需要异步处理,在这种情况下,async已经包括了:
http://caolan.github.io/async/docs.html#times
http://caolan.github.io/async/docs.html *
const async = require('async');
async.times(5, function(n, next) {
createUser(n, function(err, user) {
next(err, user);
});
}, function(err, users) {
// we should now have 5 users
});
These 'times' features arent very useful for most application code, but should be useful for testing.
这些“times”特性对于大多数应用程序代码并不是很有用,但是对于测试应该是有用的。
#14
0
Just use a nested loop (maybe enclosed in a function)
只需使用嵌套循环(可能包含在函数中)
function times( fct, times ) {
for( var i=0; i<times.length; ++i ) {
for( var j=0; j<times[i]; ++j ) {
fct();
}
}
}
Then just call it like this:
然后这样称呼它:
times( doSomething, [1,2,3] );
#15
0
const loop (fn, times) => {
if (!times) { return }
fn()
loop(fn, times - 1)
}
loop(something, 3)
#16
0
Given a function something
:
给定一个函数有:
function something() { console.log("did something") }
And a new method times
added to the Array
prototype:
在阵列原型中增加了一种新的方法时间:
Array.prototype.times = function(f){
for(v of this)
for(var _ of Array(v))
f();
}
This code:
这段代码:
[1,2,3].times(something)
Outputs this:
输出:
did something
did something
did something
did something
did something
did something
Which I think answers your updated question (5 years later) but I wonder how useful it is to have this work on an array? Wouldn't the effect be the same as calling [6].times(something)
, which in turn could be written as:
我想这能回答你更新后的问题(5年后),但是我想知道在数组上做这项工作有多有用?它的效果不是和调用[6].times(某物)一样吗?
for(_ of Array(6)) something();
(although the use of _
as a junk variable will probably clobber lodash or underscore if you're using it)
(虽然将_作为垃圾变量使用,如果您使用它,很可能会造成大量的破折号或下划线)