Javascript 做 <something> N 次(声明式语法)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10993824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
do <something> N times (declarative syntax)
提问by BreakPhreak
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
更新:澄清 - 我想something()
为每个数组元素迭代分别调用 1,2 和 3 次
采纳答案by vinyll
This answer is based on Array.forEach
, without any library, just native vanilla.
这个答案基于Array.forEach
,没有任何库,只是 native vanilla。
To basically call something()
3 times, use:
要基本上调用something()
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:
要完成这个问题,这里有一种方法可以something()
分别调用1、2 和 3 次:
It's 2017, you may use ES6:
现在是 2017 年,你可以使用 ES6:
[1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
something()
}))
or in good old ES5:
或在旧的 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)
(一次,然后两次,然后3次)
回答by ahren
Just use a loop:
只需使用循环:
var times = 10;
for(var i=0; i < times; i++){
doSomething();
}
回答by nverba
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 }`)
});
});
Update:
更新:
Taken from filling-arrays-with-undefined
This seems to be a more optimised way of creating the initial array, I've also updated this to use the second parameter map function suggested by @felix-eve.
这似乎是创建初始数组的更优化方法,我还更新了它以使用@felix-eve 建议的第二个参数映射函数。
Array.from({ length: 3 }, (x, i) => {
something();
});
回答by ggozad
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
回答by Tho
You can use lodash:
您可以使用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);
Refer to this linkfor lodash
installation
参考此链接进行lodash
安装
回答by vsync
Create an Array and fill
all items with undefined
so map
method could work:
创建一个数组,fill
所有使用undefined
somap
方法的项目都可以工作:
Array.fill
has no IE support
Array.fill
不支持 IE
Array(5).fill().map(()=>{
// Do this 5 times:
console.log(111)
})
Using old-school reveres loop:
使用老式的崇敬循环:
for( let i=5; i--; ){
// Do this 5 times:
console.log(222)
}
回答by Ozay Duman
You can also do the same thing with destructuring as follows
你也可以用如下解构做同样的事情
[...Array(3)].forEach( _ => console.log('do something'));
or if you need index
或者如果你需要索引
[...Array(3)].forEach(( _, index) => console.log('do something'));
回答by Andreas Bergstr?m
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,你可以自己实现。通过将新方法附加到 Number 和 String 原型,你可以这样做(使用 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;
回答by Machu
you can use
您可以使用
Array.forEach
数组.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);
});
回答by XU3352
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);