【问题标题】:ES6 For each/map students gradesES6 For each/map 学生成绩
【发布时间】:2018-06-02 21:01:51
【问题描述】:

需要你的小提示 - 新手在这里。

我有一个包含学生姓名和考试成绩的示例数组。

我需要执行检查学生是否通过考试的功能(假设分数 >= 80 足以通过)并且在这两种情况下它都会显示正确的信息 - “通过”或“未通过” ”。

我需要使用 .map 结构或“for each”循环来执行此操作。

如果您能帮助我,我将不胜感激 :)

var students = [['David', 80], ['Vinoth', 77], ['Divya', 88], ['Ishitha', 95], ['Thomas', 68]];

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 有很多答案,但他们已经猜到了你所期望的结果。

标签: javascript foreach ecmascript-6 functional-programming mapping


【解决方案1】:

您可以尝试使用Array.map 函数:

students.map([name, score] => ({name, score, passed: score >= 80}));

【讨论】:

  • 别忘了你可以存储这个表达式的结果!很好的答案!
【解决方案2】:

是的,只需遍历所有学生:

 for(const [name, score] of students) {
   //...
 }

现在您只需根据分数登录即可获得所需的信息:

 if(true /*?*/) {
   console.log(name + " did pass");
 } else {
  console.log(name + " did not pass");
 }

不,这还不行,我遗漏了一些东西让你解决...... :)

【讨论】:

    【解决方案3】:

    我不确定您是要使用相同的(只是丰富的)数据结构还是只是输出,但如果您想在现有的嵌套数组上构建结果:

    students = students.map(s => { 
      return [s[0], s[1], s[1] >= 80 ? 'passed' : 'not passed'];
    });
    

    如果您只想输出学生姓名:通过/未通过,您可以改用 forEach

    【讨论】:

      【解决方案4】:
      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
      <script>
        $(function(){
                var students = [['David', 80], ['Vinoth', 77], ['Divya', 88], ['Ishitha', 95], ['Thomas', 68]];
                for (var i = 0; i < students.length; ++i) {
                     var item = students[i];
                     if(item[1]>= 80){
                        console.log(item[0] + ": Passed.");
                     }else{
                         console.log(item[0] + ": Didn't pass.");
                     }
      
                }
           });
      </script>
      

      结果:

      David: Passed.
      Vinoth: Didn't pass.
      Divya: Passed.
      Ishitha: Passed.
      Thomas: Didn't pass.
      

      【讨论】:

        猜你喜欢
        • 2013-02-10
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多