简单的javascript-如何使代码更高效?

时间:2015-10-13 19:52:08

标签: javascript

我正在尝试使用javascript按一群人的年龄进行过滤。我有一个对象中的人员列表,以及人们点击时允许他们按年龄过滤的按钮列表。

这是我的代码:

HTML:

<div id="people">
    <button id="all">All</button>
    <button id="tenunder">10 and under</button>
    <button id="twentyunder">20 and under</button>
    <button id="over20">over 20</button>
</div>
<div id="people-list"></div>

使用Javascript:

    var people = [{
    name: "Derik Scott",
    age: 10,
    dob: "June 11, 1989"
}, {
    name: "Amy Sanchez",
    age: 12,
    dob: "January 11, 1989"
}, {
    name: "Kara Patil",
    age: 25,
    dob: "April 20, 1989"
}, {
    name: "Jasmine Lucas",
    age: 20,
    dob: "December 1, 1989"
}];

var peopleDiv = document.getElementById('people');

peopleDiv.addEventListener('click', function (e) {
    e.preventDefault();
    var clicked = e.target;
    var clickedId = clicked.id;
    var peopleListDiv = document.getElementById('people-list');
    clicked.className = "active";

    peopleListDiv.innerHTML = "";

    switch (clickedId) {
        case "all":
            for (var i = 0; i < people.length; i += 1) {
                peopleListDiv.innerHTML += people[i].name + "<br />";
            }
            break;
        case "tenunder":
            clicked.setAttribute("class", "active");
            for (var i = 0; i < people.length; i += 1) {
                if (people[i].age <= 10) {
                    peopleListDiv.innerHTML += people[i].name + "<br />";
                }
            }
            break;
        case "twentyunder":
            for (var i = 0; i < people.length; i += 1) {
                if (people[i].age <= 20) {
                    peopleListDiv.innerHTML += people[i].name + "<br />";
                }
            }
            break;
        case "over20":
            for (var i = 0; i < people.length; i += 1) {
                if (people[i].age > 20) {
                    peopleListDiv.innerHTML += people[i].name + "<br />";
                }
            }
            break;
    }
});

有没有办法让这段代码更有效率?

2 个答案:

答案 0 :(得分:1)

执行时间有效吗?这里最明显的瓶颈是在每次迭代中附加element.innerHTML,您可以将名称推送到数组中并在循环后写入一次:

var names = [];
for (var i = 0; i < people.length; i += 1) {
    if (people[i].age > 20) {
        names.push( people[i].name );
    }
}
peopleListDiv.innerHTML = names.join("<br />");

您还可以使用Array.prototype.filter来过滤数组,这可能不会更快,但能够一目了然地清楚地展示代码的意图:

 var names = people.filter( function( person ){
    return person.age > 20;
 })
 .map(function( person ){ return person.name });
 peopleListDiv.innerHTML = names.join("<br />");

编辑:如果您感觉很冒昧,喜欢短代码,请使用ES2015!

 peopleListDiv.innerHTML = people.filter(person => person.age > 20)
 .map(person => person.name).join('<br>')

答案 1 :(得分:1)

使用内置过滤器和地图数组方法来获得更清晰的代码。

var people = [
{name : 'John Doe', age : 21},
{name : 'Jane Doe', age : 19},
{name : 'Baby Doe', age : 2},
{name : 'kid Doe', age : 11}
];

var peopleDiv = document.getElementById('people');

peopleDiv.addEventListener('click', function (e) {
    e.preventDefault();
    var clicked = e.target;
    var clickedId = clicked.id;
    var peopleListDiv = document.getElementById('people-list');
    clicked.className = "active";

    var peopleToDisplay = getPeople(people, clickedId)
        .map(function (people) { return people.name; })
        .join('<br />');

    peopleListDiv.innerHTML = peopleToDisplay;    

});
var getPeople = function(people, clickedId) {
     switch (clickedId) {
        case "all":
            return people;
        case "tenunder":
            return people.filter(peopleUnderTen);
        case "twentyunder":
            return people.filter(peopleUnderTwenty);   
        case "over20":
            return people.filter(peopleOverTwenty);
    }   
};

var peopleUnderAge = function (age, people) {
    return function (people) {
        return people.age <= age;
    };
};

var peopleUnderTen = peopleUnderAge(10);
var peopleUnderTwenty = peopleUnderAge(20);
var peopleOverTwenty = function (people) { return people.age > 20; };

工作jsfiddle exemple