js数组sort方法
Posted 道高一尺
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
以上是关于js数组sort方法的主要内容,如果未能解决你的问题,请参考以下文章