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

【已解决】js中对于数组的for循环中是否有类似于Python中的enumerate

JS crifan 3406浏览 0评论

折腾:

【已解决】内容管理系统的统计列表中只列当前组的用户

期间,想要对于js中的数组:

去for循环,同时希望获取index

所以想到了:

js中是否有python中的,对于数组之类的enumerate

js enumerate

javascript – What is the ES6 equivalent of Python ‘enumerate’ for a sequence? – Stack Overflow

Array.prototype.entries()

Array.prototype.entries() – JavaScript | MDN

但是依旧不太好用:

      for(let curIdx, curFunctionGroupName of functionGroupNames.entries()){

会报错。

所以继续搜:

js array entries example

JavaScript Array entries() Method

JavaScript ES6 — Learn Array.keys, Array.values, and Array.entries

Object.keys, values, entries

Object.entries(user) = [ ["name","John"], ["age",30] ]

感觉应该写成:for中每个都是 keyValueList

Array.prototype.entries() – JavaScript | MDN

后来自己去回复了:

javascript – What is the ES6 equivalent of Python ‘enumerate’ for a sequence? – Stack Overflow

for(let curIndexValueList of someArray.entries()){

  console.log("curIndexValueList=", curIndexValueList)

  let curIndex = curIndexValueList[0]

  let curValue = curIndexValueList[1]

  console.log("curIndex=", curIndex, ", curValue=", curValue)

}

等价于python代码:

for curIndex, curValue in enumerate(someArray):

  print("curIndex=%s, curValue=%s" % (curIndex, curValue))

}

【总结】

最后用代码:

    if (functionGroupNames && functionGroupOwners && functionGroupIDs) {

      let functionGroupInfoDictList = []

      for(let curKeyValueList of functionGroupNames.entries()){

        console.log("curKeyValueList=", curKeyValueList)

        let curIdx = curKeyValueList[0]

        let curGroupName = curKeyValueList[1]

        console.log("curIdx=", curIdx, "curGroupName=", curGroupName)

        let curGroupOwner = functionGroupOwners[curIdx]

        let curGroupId = functionGroupIDs[curIdx]

        console.log("curGroupOwner=", curGroupOwner, "curGroupId=", curGroupId)

        let curGroupInfoDict = {

          "groupId": curGroupId,

          "groupName": curGroupName,

          "groupOwnerName": curGroupOwner,

        }

        functionGroupInfoDictList.push(curGroupInfoDict)

      }

      console.log("functionGroupInfoDictList=", functionGroupInfoDictList)

    }

核心部分是:

      for(let curKeyValueList of functionGroupNames.entries()){

        let curIdx = curKeyValueList[0]

        let curGroupName = curKeyValueList[1]

效果是:

转载请注明:在路上 » 【已解决】js中对于数组的for循环中是否有类似于Python中的enumerate

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.196 seconds, using 22.13MB memory