亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在JS中按價格對項目數組進行排序忽略具有相同價格的元素

在JS中按價格對項目數組進行排序忽略具有相同價格的元素

繁花如伊 2023-06-29 15:38:56
我正在嘗試使用 Javascript 訂購產品列表,并且該腳本運行良好,但如果兩種產品具有相同的價格,則腳本只會忽略其中一個。function myFunction() {var items = document.querySelectorAll('.vc_visible-item');var y = document.getElementsByClassName('vc_pageable-slide-wrapper');var parent = y[0];var SortElements = new Object();items.forEach(function(item, indx){  var itemValue = parseFloat(item.querySelector('.price-product').textContent.replace('€', '').replace(/\s+/g, ''));  SortElements[itemValue] = {'element': item, 'index': indx} ;});var keys = Object.keys(SortElements);function compareNumeric(a, b) {  a = parseInt(a);  b = parseInt(b);  if (a <= b) return 1;  if (a >= b) return -1; }keys.sort(compareNumeric);keys.map(function(key, indx){  parent.insertAdjacentElement('beforeend', SortElements[key]['element']);});}有人對我如何解決這個問題有任何建議嗎?非常感謝!
查看完整描述

2 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

您的問題不在于“排序”,而是您覆蓋了 SortElements 對象中的鍵


SortElements[itemValue] = {'element': item, 'index': indx}

如果下一個商品具有相同的價格,那么您將使用新的 {element, index} 覆蓋 SortElements[that Price];


我不想插入到一個對象中..插入到一個數組中


function myFunction() {

  var items = document.querySelectorAll('.vc_visible-item');

  var y = document.getElementsByClassName('vc_pageable-slide-wrapper');

  var parent = y[0];

  var SortElements = [];

  items.forEach(function(item, indx){

    var itemValue = parseFloat(item.querySelector('.price-product').textContent.replace('€', '').replace(/\s+/g, ''));

    SortElements.push({'element': item, 'price':itemValue, 'index': indx});

  });

  function compareNumeric(a, b) {

    numA = a.price;

    numB = b.price;


    if (numA < numB) return 1;

    if (numA > numB) return -1;

    return 0;

  }

  SortElements.sort(compareNumeric);

  SortElements.forEach(function(item){

    parent.insertAdjacentElement('beforeend', item.element);

  });

}


查看完整回答
反對 回復 2023-06-29
?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

在循環中,您使用項目的值作為每個屬性的名稱在對象items.forEach中創建成員。SortElements如果循環發現具有該名稱的成員已存在,它將用遇到的新值替換該屬性的當前值。您可以在該行周圍放置一個條件來檢查該屬性是否存在。



查看完整回答
反對 回復 2023-06-29
  • 2 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號