通过映射比较列表中的所有值

时间:2018-08-29 22:02:00

标签: javascript typescript react-redux

我有一个条件语句来比较该值是否为错误。我有一个值列表,我需要一种方法来编写条件语句来检查列表中的所有值。这是存储值列表的代码:

screenshot of code with the debugger showing the contents of this.props.notificationList

我正在写下面的条件代码,但是我只能得到数组中的第一个元素。我需要一种可能的方法来检查整个列表并在此处进行比较。

this.props.notificationList[0].Level === "error" 

2 个答案:

答案 0 :(得分:1)

  

我有一个值列表,我需要一种方法来编写条件语句以检查列表中的所有值此代码存储值列表

  • 如果单个错误是失败

使用Array.prototype.some:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

例如this.props.notificationList[0].Level === "error"变为:

this.props.notificationList.some(n => n.Level==="error");
  • 如果所有错误均被视为失败

使用every代替some

答案 1 :(得分:0)

要返回一个新的有序数组,其中新数组中的每个项目都是相应项目是否有错误:

const errorsList = this.props.notificationList.map(item => item.Level === "error");

要返回一个布尔值以指示是否有任何错误

const anyError = this.props.notificationList.some(item => item.Level === "error");