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);
});
}

TA貢獻1788條經驗 獲得超4個贊
在循環中,您使用項目的值作為每個屬性的名稱在對象items.forEach
中創建成員。SortElements
如果循環發現具有該名稱的成員已存在,它將用遇到的新值替換該屬性的當前值。您可以在該行周圍放置一個條件來檢查該屬性是否存在。
添加回答
舉報