相当于Javascript中python的范围



我想知道python的范围(start,stop,step=1(的等效代码是什么。如果有人知道,我真的很感激你的帮助。

您可以尝试以下代码,但需要先创建一个函数:

var number_array = [];
function range(start,stop) {
for (i =start; i < (stop+1); i++) {
number_array.push(i);
}
return number_array;
}

JavaScript 没有 range 方法。 请参考 MDN JavaScript 指南中的循环代码部分 了解更多信息。

此外,在提出此类问题之前,请尝试进行一些研究或举例说明您想要实现的目标。代码是示例或简单的描述就足够了。

range()的惰性计算版本; 过去xrange();

function* range(start, end, step) {
const numArgs = arguments.length;
if (numArgs < 1) start = 0;
if (numArgs < 2) end = start, start = 0;
if (numArgs < 3) step = end < start ? -1 : 1;
// ignore the sign of the step
//const n = Math.abs((end-start) / step);
const n = (end - start) / step;
if (!isFinite(n)) return;
for (let i = 0; i < n; ++i)
yield start + i * step;
}
console.log("optional arguments:", ...range(5));
console.log("and the other direction:", ...range(8, -8));
console.log("and with steps:", ...range(8, -8, -3));
for(let nr of range(5, -5, -2)) 
console.log("works with for..of:", nr);
console.log("and everywhere you can use iterators");
const [one, two, three, four] = range(1,4);
const obj = {one, two, three, four};
console.log(obj)
.as-console-wrapper{top:0;max-height:100%!important}

最新更新