比较数组的每个元素以进行反应状态

时间:2019-06-11 13:44:38

标签: arrays reactjs

嗨,我不知道如何将数组的每个元素与状态进行比较:

enter image description here

doesCustomerExist = () => {
  const { customers } = this.props;
  let result = customers.map(c => c.phone)
  if(result === this.state.phone)
    return (console.log('already exist'))
    console.log(result)
}

2 个答案:

答案 0 :(得分:1)

您可以使用indexOf检查数组是否包含给定元素。

例如:

const phone = "123";
const customers = ["111", "222", "333", "123"];

const isInArray = customers.indexOf(phone) > -1;

console.log(isInArray);

答案 1 :(得分:1)

为此,只需使用Array.inlcudes

const phone = "123";
const customers = ["111", "222", "333", "123"];

const isFound = customers.includes(phone)

console.log(isFound);