React Native - 如何查找数组中的某个值是否与另一个数组中的某个值匹配?

时间:2018-05-24 13:03:37

标签: arrays reactjs if-statement react-native

我找到并试用了.includes来帮助解决这个问题。但是.includes并没有按照我的意图行事。它确实发现数组中的哪个值与另一个数组中的值匹配,但它只匹配相似值

使用逗号映射的result_postid结果

[10,22,12,36,45,206]

使用逗号映射的item.id结果

[5,13,28,136,400,538]

我试图找出为什么某些值在true明确false时仍然会返回.includes。然后我得出结论:36实际上正在从result_postid获取 136 并将其与 item.id 匹配.includes。这是我使用{result_postid.includes(item.id) ? <Text>True</Text> : <Text>False</Text> } 设置if语句的方法:

result_postid | item.id | Result

10 != 5,13,28,136,400,538: False
22 != 5,13,28,136,400,538: False
12 != 5,13,28,136,400,538: False
36 =  5,13,28,136,400,538: True <--- this should be false
45 != 5,13,28,136,400,538: False
206 != 5,13,28,136,400,538: False

结果如下:

map

是否有可能找到数组中的某个值是否与另一个数组中的某个值完全匹配?

这是我在render() { const result_postid = this.state.data_one.map(function(val) { return val.postid; }).join(','); } [{"spaceid":"16","postid":"10"},{"spaceid":"16","postid":"22"},{"spaceid":"16","postid":"12"},{"spaceid":"16","postid":"36"},{"spaceid":"16","postid":"45"},{"spaceid":"16","postid":"206"}] 之前看到的result_postid:

resolveWithFullResponse: true

1 个答案:

答案 0 :(得分:0)

您可以使用.some.findIndex来实现相同的

const postId = [10,22,12,36,45,206]
const itemId = [5,13,28,136,400,538]
const res = postId.some(id => itemId.findIndex(elem => elem === id) > -1);
console.log(res)

用于渲染pupose

render() {
   const isPresent = result_postid.some(id => item_id.findIndex(elem => elem === id) > -1);
   return (
      <View>
          {isPresent? <Text>True</Text>:<Text>False</Text>}
      </View>
   )
}