在网站中排序对象

时间:2015-12-04 03:16:37

标签: javascript

这是一些关于我的问题的一些javascript。



//Creation of objects
//food
 var p1 = new product(1, "oreo.jpg", "Pumpkin Spice Oreo", 14.99);
array.push(p1);
var p2 = new product(2, "hershey.jpg", "Hershey's Kisses, Pumpkin Spice", 6.99);
array.push(p2);
var p3 = new product(3, "psl.jpg", "Pumpkin Spice Latte Keurig", 13.92);
array.push(p3);
var p4 = new product(4, "psc.jpg", "Pumpkin Spice Cookie Mix", 10.99);
array.push(p4);
var p5 = new product(5, "hotcocoa.jpg", "Hot Cocoa - Pumpkin Spice", 17.50);
array.push(p5);
var p6 = new product(6, "pssyrup.jpg", "Pumpkin Pie Syrup", 13.79);
array.push(p6);

//Clothing
var p7 = new product(7, "fedora.jpg", "Ugly Fedora", 13.70);
array.push(p7);
var p8 = new product(8, "fedora2.jpg", "Even uglier fedora", 17.99);
array.push(p8);
var p9 = new product(9, "frytshirt.jpg", "Hipster Fries Sweather", 36.99);
array.push(p9);
var p10 = new product(12, "frieshat.jpg", "Fries Bucket Hat", 29.99);
array.push(p10);
var p11 = new product(11, "unicorno.jpg", "Unicorn Onesie", 30.99);
array.push(p11);
var p12 = new product(10, "unicornm.jpg", "Unicorn Mask", 17.99);






function showProduct(id) {
  var obj = searchArray(id);

  var div1 = document.createElement("div");
  var attdiv = document.createAttribute("class");
  attdiv.value = "pdiv";
  div1.setAttributeNode(attdiv);

  var img = document.createElement("img")
  var classimg = document.createAttribute("class");
  classimg.value = "pimg";
  img.setAttributeNode(classimg);
  img.src = obj.sourc;
  div1.appendChild(img);


  var name = document.createElement("p");
  var classp = document.createAttribute("class");
  classp.value = "pp";
  name.setAttributeNode(classp);
  name.innerHTML = obj.name;
  div1.appendChild(name);

  var price = document.createElement("p");
  price.innerHTML = obj.price;
  div1.appendChild(price);

  var inputElement = document.createElement('input');
  inputElement.type = "button"
  inputElement.value = "Add to cart"
  inputElement.addEventListener('click', function() {
    document.cookie = "cart" + id + "=" + id;

  });
  div1.appendChild(inputElement);

  var main = document.getElementById("main");
  main.appendChild(div1);

}




我想按价格和名称对这些项目进行排序,然后为每个类别显示。我是否应该为每个类别的项目创建一个数组,或者即使所有产品都在同一个数组中,我仍然可以对它们进行排序吗?

谢谢

2 个答案:

答案 0 :(得分:0)

如果所有产品都在同一个数组中,您仍然可以对它们进行排序。您只需要提供适用于两种类型对象的排序规则。



var obj1 = {name: 'Larent', age: 30};
var obj2 = {name: 'James', age: 20};
var obj3 = {name: 'Wanda', age: 50};

var personArr = [obj1, obj2, obj3];
//order by name
personArr.sort(function(item1, item2){
    return item1.name > item2.name;
})

console.log(personArr);
//output: [ { name: 'James', age: 20 },
//   { name: 'Larent', age: 30 },
//   { name: 'Wanda', age: 50 } ]
//order by age
personArr.sort(function(item1, item2){
    return item1.age > item2.age;
})
console.log(personArr);
//output: [ { name: 'James', age: 20 },
//   { name: 'Larent', age: 30 },
//   { name: 'Wanda', age: 50 } ]




答案 1 :(得分:0)

我认为您将需要进行一些重构才能使排序正常有效地运行。这就是我如何摆脱困境:

// Set up a basic list from which to work
var preArray = [
    {id:1, image:"oreo.jpg",        desc:"Pumpkin Spice Oreo",          price:14.99},
    {id:1, image:"psl.jpg",         desc:"Pumpkin Spice Latte Keurig",  price:13.92},
    {id:5, image:"hotcocoa.jpg",    desc:"Hot Cocoa - Pumpkin Spice",   price:17.50}
];

// Now do your sorting
// sortOn sorts the array "in place", so you just have to call it.
sortOn(preArray, "price");
sortOn(preArray, "desc");

// Then generate your product and DOM stuff
var postArray = [];
for( var i=0; i<preArray.length; i++){
    var item = preArray[i];
    postArray.push( new product(item.id, item.image, item.desc, item.price) );
}

你需要这个方便的排序功能(我经常使用这个人):

function sortOn (arr, prop, reverse, numeric) {

    // Ensure there's a property
    if (!prop || !arr) {
        return arr
    }

    // Set up sort function
    var sort_by = function (field, rev, num) {

        var primer = num ? function(val){
            return parseFloat(String(val).replace(/[^0-9.\-]+/g, ''));
        } : function(val){
            return String(val).toLowerCase();
        }

        var r = rev ? -1 : 1;

        // Return the required a,b function
        return function (a, b) {

            // Reset a, b to the field
            a = primer(a[field]), b = primer(b[field]);

            if(num){
                return (a-b) * r;
            } else {
                return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * r;
            }

        };

    }

    // Distinguish between numeric and string to prevent 100's from coming before smaller
    // e.g.
    // 1
    // 20
    // 3
    // 4000
    // 50

    arr.sort( sort_by(prop, reverse, numeric) );


}