7 Object类型

1 访问对象属性的方式有几种?

方式有两种。一般多用表示法

 

2 对象排序:将下面四个学生按照得分,从低到高进行排序。

var person = [{name: "A", score: 10},
    {name: "D", score: 40},
    {name: "B", score: 20},
    {name: "C", score: 30}];

// before sort
person.forEach( function(item, index, array) {
    document.write(item.name + " " + item.score +"<br>");
});
document.write("<hr>");

// sorting
person.sort(compare("score"));

function compare(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;
        }
    };
}
// after sort
person.forEach( function(item, index, array) {
    document.write(item.name + " " + item.score +"<br>");
});

 

posted on 2017-03-24 14:45  modDx  阅读(105)  评论(0编辑  收藏  举报

导航