tips:用閉包優雅地寫出json排序方法。

	function createComparisonFunction(propertyName) {
        
            return function(object1, object2){
                var value1 = object1[propertyName];
                var value2 = object2[propertyName];
        
                if (value1 < value2){
                    return -1;
                } else if (value1 > value2){
                    return 1;
                } else {
                    return 0;
                }
            };
        }

        var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age: 29}];
        
        data.sort(createComparisonFunction("name"));
        alert(data[0].name);  //Nicholas
        
        data.sort(createComparisonFunction("age"));
        alert(data[0].name);  //Zachary 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章