最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】js中实现类似于Python中的Range

JS crifan 1203浏览 0评论
reactjs中js中有个列表:
this.state.dialogList
想要实现类似于Python中的range
且是倒叙,5,4,3,2,1的那种
然后去处理。
js python range
JavaScript function similar to Python range() – Stack Overflow
arrays – Does JavaScript have a method like “range()” to generate a range within the supplied bounds? – Stack Overflow
在JavaScript中实现类似于Python的range()函数 | The Bloom of Youth | 锦瑟华年
【总结】
最后用:
  console.log(`range: start=${start}, stop=${stop}, step=${step}`)

  let realStop = stop
  let realStart = start
  let realStep = step

  if (typeof realStop === 'undefined') {
      // one param defined
      realStop = realStart
      realStart = 0
  }

  if (typeof realStep === 'undefined') {
    realStep = 1
  }
  console.log(`range: start=${start}, stop=${stop}, step=${step}`)

  if ((realStep > 0 && realStart >= realStop) || (realStep < 0 && realStart <= realStop)) {
      // return []
      return [realStart]
  }

  const result = []
  for (let i = realStart; realStep > 0 ? i < realStop : i > realStop; i += realStep) {
      result.push(i)
  }

  return result
}
实现了需要的效果。
其中当:realStart >= realStop
比如:
range(0, 0, -1)
也可以返回:
[0]

转载请注明:在路上 » 【已解决】js中实现类似于Python中的Range

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.173 seconds, using 22.09MB memory