2024-04-23 18:41:58 发布
网友
我想知道python的范围(start,stop,step=1)的等效代码是什么。如果有人知道,我真的很感谢你的帮助。你知道吗
延迟评估版本的range();以前是xrange()
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)
您可以尝试此代码,但需要先创建一个函数:
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指南中的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)
; ^{pr2}$ ;您可以尝试此代码,但需要先创建一个函数:
JavaScript没有range方法。 请参阅MDN的JavaScript指南中的Looping Code部分 更多信息。你知道吗
另外,在提出这样的问题之前,试着做一些研究或者举一些你想达到的目标的例子。一个代码是示例,或者一个简单的描述就足够了。你知道吗
相关问题 更多 >
编程相关推荐