首页 > 解决方案 > 字典无法在赛普拉斯中排序

问题描述

我最近一直在努力学习 Cypress,我必须做一个练习。基本上我想获取某个产品的价格,将它们添加到带有键、值对的字典中,然后对该字典进行排序。我找不到问题,我问你是否可以给我一些见解。

var cardContent = 'div.card-v2-content';
var cardPrice = 'p.product-new-price';
var dict = [];

checkPrices() {

        cy.get(cardContent).each($el => {
            //Loop through each DOM element and find the price of the product
            var eachProductPrice = $el.find(cardPrice);
            var stringPrice = eachProductPrice.text();
            var replacedPrice = stringPrice.replace('.', '').replace('Lei','').replace('de la','').trim();
            var priceNumber = parseFloat(replacedPrice);
            //cy.log(priceNumber)
            
            dict.push($el, priceNumber);


        }).then(() => {

            cy.log('sorting') //Starts the sorting process

            // Create items array
            var items = Object.keys(dict).map(function (key) {
                return [key, dict[key]];
            });

            // Sort the array based on the second element

            var items = (items.push(items.sort(function (first, second) {
                return second[1] - first[1];
            })));


        })

标签: node.jscypress

解决方案


排序部分应该是

  // sort is an in place sort, that means that the items will be rearranged
  // just this is ok 
  items.sort(function (first, second) {
       return second[1] - first[1];
  }))

查看链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort了解有关 Array.sort 的更多信息


推荐阅读