開発環境
- OS X Mavericks - Apple(OS)
- Safari, Firefox + Firebug, Google Chrome(Webプラウザ、プラグイン)
- BBEdit - Bare Bones Software, Inc. (GUI) , Emacs (CUI) (Text Editor)
- JavaScript (プログラミング言語)
Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 10(Liberated functions: First Class Functions)、EXERCISE(p.463)を解いてみる。
EXERCISE(p.463)
コード(BBEdit, Emacs)
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 } ], compareName = function (colaA, colaB) { var nameA = colaA.name, nameB = colaB.name; if (nameA < nameB) { return -1; } if (nameA === nameB) { return 0; } return 1; }, compareCalories = function (colaA, colaB) { return colaA.calories - colaB.calories; }, compareColor = function (colaA, colaB) { var colorA = colaA.color, colorB = colaB.color; if (colorA < colorB) { return -1; } if (colorA === colorB) { return 0; } return 1; }, printProducts = function (products) { var i, max, output = '', product; for (i = 0, max = products.length; i < max; i += 1) { product = products[i]; output += 'Name: ' + product.name + ', Calories: ' + product.calories + ', Color: ' + product.color + ', Sold: ' + product.sold + '\n'; } print(output); }; products.sort(compareName); print('Products sorted by name:'); printProducts(products); products.sort(compareCalories); print('Products sorted by calories:'); printProducts(products); products.sort(compareColor); print('Products sorted by color:'); printProducts(products);
0 コメント:
コメントを投稿