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

在Cypress中对存储商品价格的字典排序失败问题求助

代码问题排查与修正方案

核心错误点

  • 数据结构不符需求:声明的dict为数组类型,无法满足键值对存储要求,若要使用字典请声明为普通对象{},更推荐直接使用对象数组简化后续排序逻辑
  • 数据存入逻辑错误:dict.push($el, priceNumber)会将DOM元素、价格作为两个独立元素插入数组,二者没有形成关联关系
  • 排序逻辑错误:items.push(items.sort(...))写法错误,Array.sort()会直接修改原数组并返回排序后的数组,套一层push会导致items最终被赋值为数组长度值,排序结果丢失
  • 键名使用隐患:直接使用DOM元素$el作为字典键会被自动转为[object Object]字符串,所有键重名无法正常存储多组数据,建议使用商品名称等唯一标识作为键

修正后可运行代码

const cardContent = 'div.card-v2-content';
const cardPrice = 'p.product-new-price';
// 直接使用对象数组存储,排序和取值都更便捷
const productList = [];

function checkPrices() {
  cy.get(cardContent).each($el => {
    // 提取价格并转成数字格式
    const eachProductPrice = $el.find(cardPrice);
    const stringPrice = eachProductPrice.text();
    const replacedPrice = stringPrice.replace('.', '').replace('Lei','').replace('de la','').trim();
    const priceNumber = parseFloat(replacedPrice);
    // 存入关联后的对象
    productList.push({
      element: $el,
      price: priceNumber
    });
  }).then(() => {
    cy.log('开始排序')
    // 按价格降序排序
    productList.sort((first, second) => second.price - first.price);
    // 输出排序结果验证
    productList.forEach((item, index) => {
      cy.log(`第${index+1}名价格:${item.price}`)
    })

    // 如果确实需要键值对字典格式,排序后再生成即可
    const sortedPriceDict = {}
    productList.forEach((item, index) => {
      // 这里可以替换为你提取的商品名称作为键,当前用序号做演示
      sortedPriceDict[`product_${index}`] = item.price
    })
    cy.log('排序后的键值对字典:', sortedPriceDict)
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:24:05