gpt4 book ai didi

javascript - 是否有一种机制可以在没有可变变量的情况下在 ES6 (ECMAScript 6) 中循环 x 次?

转载 作者:IT王子 更新时间:2023-10-29 02:38:47 25 4
gpt4 key购买 nike

在 JavaScript 中循环 x 次的典型方法是:

for (var i = 0; i < x; i++)
doStuff(i);

但我根本不想使用 ++ 运算符或任何可变变量。那么,在 ES6 中,有没有办法以另一种方式循环 x 次?我喜欢 Ruby 的机制:

x.times do |i|
do_stuff(i)
end

JavaScript/ES6 中有类似的东西吗?我可以作弊并制作我自己的发电机:

function* times(x) {
for (var i = 0; i < x; i++)
yield i;
}

for (var i of times(5)) {
console.log(i);
}

当然我还在用i++。至少它是看不见的:),但我希望 ES6 中有更好的机制。

最佳答案

使用 ES2015 Spread operator :

[...数组(n)].map()

const res = [...Array(10)].map((_, i) => {
return i * 10;
});

// as a one liner
const res = [...Array(10)].map((_, i) => i * 10);

或者如果您不需要结果:

[...Array(10)].forEach((_, i) => {
console.log(i);
});

// as a one liner
[...Array(10)].forEach((_, i) => console.log(i));

或者使用 ES2015 Array.from operator :

Array.from(...)

const res = Array.from(Array(10)).map((_, i) => {
return i * 10;
});

// as a one liner
const res = Array.from(Array(10)).map((_, i) => i * 10);

请注意,如果您只需要重复一个字符串,您可以使用 String.prototype.repeat .

console.log("0".repeat(10))
// 0000000000

关于javascript - 是否有一种机制可以在没有可变变量的情况下在 ES6 (ECMAScript 6) 中循环 x 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com