js数组sort方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> var products = [ { name: "Grapefruit", calories: 170, color: "red", sold: 8200 }, { name: "Orange", calories: 160, color: "orange", sold: 12101 }, { name: "Cola", calories: 210, color: "caramel", sold: 25412 }, { name: "Diet Cola", calories: 0, color: "caramel", sold: 43922 }, { name: "Lemon", calories: 200, color: "clear", sold: 14983 }, { name: "Raspberry", calories: 180, color: "pink", sold: 9427 }, { name: "Root Beer", calories: 200, color: "caramel", sold: 9909 }, { name: "Water", calories: 0, color: "clear", sold: 62123 } ]; function compareSold(colaA, colaB){ if (colaA.sold > colaB.sold){ return 1; } else if (colaA.sold === colaB.sold){ return 0; } else { return -1 } } products.sort(compareSold); console.log(products); //传递给sort比较函数需要根据比较结果返回 // 如果第一项>第二项,返回大于0 // 如果第一项=第二项, 返回0 // 反之,返回小于0 </script> </head> <body> </body> </html>