【发布时间】:2019-12-20 03:39:38
【问题描述】:
我想知道 python 的 range(start,stop,step=1) 的等效代码是什么。如果有人知道,我非常感谢您的帮助。
【问题讨论】:
-
一个 for 循环。请展示您的研究。
标签: javascript python
我想知道 python 的 range(start,stop,step=1) 的等效代码是什么。如果有人知道,我非常感谢您的帮助。
【问题讨论】:
标签: javascript python
JavaScript 没有范围方法。 请参阅 MDN 的 JavaScript 指南中的 Looping Code 部分 了解更多信息。
此外,在提出此类问题之前,请尝试进行一些研究或举例说明您希望实现的目标。一个代码是示例,或者一个简单的描述就足够了。
【讨论】:
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}
【讨论】:
你可以试试这个代码,但是你需要先创建一个函数:
var number_array = [];
function range(start,stop) {
for (i =start; i < (stop+1); i++) {
number_array.push(i);
}
return number_array;
}
【讨论】: