三元if语句,否则不与&&一起使用

时间:2019-06-25 22:02:45

标签: javascript arrow-functions

我正在尝试将可以转换为箭头功能的代码转换为箭头功能(对于箭头功能,我还比较陌生),但是不知道为什么它不适用于&&。我认为三元if语句与else使用?和:而使用&&而不使用else语句。

以下原因为何不起作用:

courses.forEach((course) =>
      tutors.forEach((tutor) =>
        tutor.id == course.id &&
        course["name"] = tutor.name
        //console.log(1) has no errors
      )
    );

这行得通,在这里我不得不使用else语句,也就是: 1

courses.forEach((course) =>
      tutors.forEach((tutor) =>
        tutor.id == course.id ?
        course["name"] = tutor.name : 1
      )
    );

这是不带箭头功能的解决方案,因此基本上,解决方案是将以下内容转换为箭头功能:

courses.forEach(function(course) {
  tutors.forEach(function(tutor) {
    if (tutor.id == course.id) {
      course["name"] = tutor.name;
    }
  });
});

任何关于我在做什么的解释,或者关于如何最好地转换为箭头功能的任何技巧都是很好的。感谢您的帮助。

let tutors = [
	  {
	    name: "Beth",
	    age: 37,
      id: 1
	  },
	  {
	    name: "Bob",
	    age: 32,
      id: 2
	  },
	  {
	    name: "Jack",
	    age: 63,
      id: 3
	  },
	  {
	    name: "Jess",
	    age: 17,
      id: 4
	  }
	],
  courses = [
    {
      code: "AA01",
      description: "Javascript IIFEs, maps, filters, reduces, etc",
      id: 3
    },
    {
      code: "AO83",
      description: "Arrays, for of loops, etc",
      id: 1
    },
    {
      code: "AX40",
      description: "CSS, HTML",
      id: 3
    },
    {
      code: "BX92",
      description: "SQL, Node",
      id: 2
    },
    {
      code: "CC24",
      description: "PHP, Java",
      id: 1
    },
    {
      code: "DI30",
      description: "MongoDB",
      id: 4
    }
  ];

/*
courses.forEach(function(course) {
  tutors.forEach(function(tutor) {
    if (tutor.id == course.id) {
      course["name"] = tutor.name;
    }
  });
});
*/


courses.forEach((course) =>
  tutors.forEach(function(tutor) {
    if (tutor.id == course.id) {
      course["name"] = tutor.name;
    }
  })
);

/*
courses.forEach((course) =>
  tutors.forEach(function(tutor) {
    if (tutor.id == course.id) {
      course["name"] = tutor.name;
    }
  })
);
*/

/*
courses.forEach((course) =>
  tutors.forEach((tutor) =>
    tutor.id == course.id ?
    course["name"] = tutor.name : 1
  )
);
*/

courses.forEach((course) =>
  tutors.forEach((tutor) =>
    tutor.id == course.id &&
    course["name"] = tutor.name
    //console.log(1) has no errors
  )
);

1 个答案:

答案 0 :(得分:2)

courses.map((cours) => cours["name"] = tutors.find(tutor => tutor.id === cours.id).name)

假设每门课程的导师共享相同的ID

使用forEach

courses.forEach((cours) => cours["name"] = tutors.find(tutor => tutor.id === cours.id).name)

&&在某些情况下不起作用,因为运行时认为您正在用左侧替换该值

工作

courses.forEach((course) =>
  tutors.forEach((tutor) =>
    tutor.id === course.id &&
    (course["name"] = tutor.name)
  )
);

没有

courses.forEach((course) =>
  tutors.forEach((tutor) =>
    tutor.id == course.id &&
    course["name"] = tutor.name
  )
)