【问题标题】:React-native array check if value exist反应原生数组检查值是否存在
【发布时间】:2018-03-07 03:32:31
【问题描述】:

如何检查ticketId是否已经插入数组?

这是代码:

state = { myState: [], status: 0, limit: 5 };

  selected(ticketId) {
  if (this.state.status < this.state.limit) { 
    this.state.myState.push({ id: ticketId }); //what ever i chose get inserted
    this.state.status++;
    this.setState({ status: this.state.status }); 
    //console.log('here', this.state.status);
  } else {
    console.log('3'); //check if condition meet
  }
 }

如果ticketId 已经插入并触发警报,我如何创建条件检查myState 数组?

【问题讨论】:

    标签: javascript arrays react-native


    【解决方案1】:

    您好,您可以使用 loadash Find it Here 来解决这类问题,它既简单又好看! :)

    示例:1

    _.indexOf([1, 2, 1, 2], 2);
    // => 1
    

    或者你可以使用

    示例:2

    var users = [
      { 'user': 'barney',  'active': false },
      { 'user': 'fred',    'active': false },
      { 'user': 'pebbles', 'active': true }
    ];
    
    _.findIndex(users, function(o) { return o.user == 'barney'; });
    // => 0
    
    // The `_.matches` iteratee shorthand.
    _.findIndex(users, { 'user': 'fred', 'active': false });
    // => 1
    
    // The `_.matchesProperty` iteratee shorthand.
    _.findIndex(users, ['active', false]);
    // => 0
    
    // The `_.property` iteratee shorthand.
    _.findIndex(users, 'active');
    // => 2
    

    在您的代码中

    _.findIndex(this.state.myState, { 'id': ticketId });
    // It will return 0 if there is nothing 
    // else will return no of index 
    // where it ticketid is present 
    // you can do alert on if its not 0
    

    【讨论】:

      【解决方案2】:

      当您存储为对象 {id:value} 时,最好改用“every”。

      state = { myState: [], status: 0, limit: 5 };
      
      selected(ticketId) {
         if (this.state.status < this.state.limit ) { 
            if(this.state.myState.every((item) => item.id !== ticketId)){
              this.state.myState.push({ id: ticketId }); //what ever i chose get inserted
              this.state.status++;
              this.setState({ status: this.state.status }); 
            //console.log('here', this.state.status);
           }
         } else {
         console.log('3'); //check if condition meet
         } 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-13
        • 2016-12-29
        • 1970-01-01
        相关资源
        最近更新 更多