想要通过使用Javascripts map,reduce,foreach,filter方法来实现功能

时间:2017-01-23 07:55:17

标签: javascript arrays dictionary filter reduce

请帮我写出更好的代码。

假设我有一个如下所示的JavaScript数组:

var students = [
    { firstname: "stud1", lastname: "stud2", marks: "60" },
    { firstname: "stud3", lastname: "stud4", marks: "30" },
    { firstname: "stud5", lastname: "stud6", marks: "70" },
    { firstname: "stud7", lastname: "stud8", marks: "55" },
    { firstname: "stud9", lastname: "stud10", marks: "20" },
];

在页面上我想分两部分显示数据:1)得到分数> = 40的学生2)得到分数的学生< 40

通过使用for循环,我可以轻松完成此功能,如下所示。

var data = "";var data1 = "";
for (var i = 0; i < students.length; i++ )
{
    if(students.marks >= 40){
        data += = students.firstname + " " + students.lastname; //actual data in html div tag
        ....
    }else{
            data1 += = students.firstname + " " + students.lastname;
    }
}

我想通过使用map,reduce,foreach,filter等JavaScript方法来实现相同的功能。(想要提高我的JavaScript知识)

不确切知道哪种方法对此类功能有用。

使用map方法并尝试显示数据,但每个对象/数组的末尾都有一个尾随。

有人可以帮助/指导我编写正确的代码吗?

2 个答案:

答案 0 :(得分:1)

以下是使用filterforEach方法的解决方案,使用callback函数。

参见此处的参考资料:

&#13;
&#13;
var students = [
    { firstname: "stud1", lastname: "stud2", marks: "60" },
    { firstname: "stud3", lastname: "stud4", marks: "30" },
    { firstname: "stud5", lastname: "stud6", marks: "70" },
    { firstname: "stud7", lastname: "stud8", marks: "55" },
    { firstname: "stud9", lastname: "stud10", marks: "20" },
];
students.filter(function(item){
    return item.marks>=40;  
}).forEach(function(item){
    div=document.getElementById('persons');
    div.innerHTML+=item.firstname+' '+item.lastname+'<br>';
});
&#13;
<div id="persons"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用单个循环并添加predicate作为索引的信息。稍后加入元素以获得每个元素的刺痛。

var students = [{ firstname: "stud1", lastname: "stud2", marks: "60" }, { firstname: "stud3", lastname: "stud4", marks: "30" }, { firstname: "stud5", lastname: "stud6", marks: "70" }, { firstname: "stud7", lastname: "stud8", marks: "55" }, { firstname: "stud9", lastname: "stud10", marks: "20" }], 
    predicate = function (o) { return o.marks >= 40; },
    result = [[], []];      

students.forEach(function (a) {
    result[+predicate(a)].push(a.firstname + ' ' + a.lastname);
});
result = result.map(function (a) { return a.join(', '); });

console.log(result);