You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中each循环内如何通过索引获取Map的对应值?

问题解答

完全可以移除测试代码内部的fileSizes数组,直接复用已定义的fileSizesMap实现相同校验逻辑。

ES6及以上标准的JavaScript环境中,Map会严格保留键值对的插入顺序,你定义fileSizesMap时的顺序为excel文件→docx文件→pdf文件,和上传文件的顺序[excelFilePath, docxFilePath, pdfFilePath]、表格渲染的行顺序完全匹配,直接提取Map的所有值遍历即可,优化后的代码如下:

it('attaches many documents', () => {
  const expectedSizes = Array.from(fileSizesMap.values())
  cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])

  cy.get('div.table-body>.table-row').each(($el, index) => {
    expect($el.find('.col-upload-size')).to.contain.text(expectedSizes[index])
  })
})

如果你希望进一步提升代码健壮性,避免后续调整Map键值对顺序导致校验失效,可以显式指定和上传顺序匹配的key列表:

it('attaches many documents', () => {
  const expectedSizeKeys = ['excelFileSize', 'docxFileSize', 'pdfFileSize']
  cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])

  cy.get('div.table-body>.table-row').each(($el, index) => {
    expect($el.find('.col-upload-size')).to.contain.text(fileSizesMap.get(expectedSizeKeys[index]))
  })
})

内容的提问来源于stack exchange,提问作者JeyKey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:45:04