在反应中展开数组js

时间:2017-11-02 09:58:14

标签: javascript algorithm reactjs loops

componentWillMount(){
   this.expand();
  }
componentDidMount(){}
expand(){
var re = [];
this.state.reservation1.length = 9;
  for (var i = 0; i < this.state.reservation1.length; i++) {
     if(this.state.reservation1[i]){
       re[i]=this.state.reservation1[i]
       }
        else {
           re[i]= this.state.reservation1[i]=
              {name:"",active:false,dayindex:0}
            }
        }
   console.log(re)
  console.log(re.dayindex)

   }



constructor(props){
  super(props);
  this.state = {
    reservation1:[
      {name:"8:30",active:true,dayindex:1},
      {name:"jad",active:true,dayindex:3},
      {name:"tony",active:true,dayindex:4},
      {name:"",active:false,dayindex:6},
    ],
    reservations:[]
  };
  this.expand=this.expand.bind(this);
}

RE返回9个对象的阵列 re.dayindex未定义 请有人帮忙吗

我正在尝试扩展此数组以按dayindex重新排序 任何解决方案都会很高兴

1 个答案:

答案 0 :(得分:1)

您正尝试访问数组中的对象。所以它应该是re[i].dayindex,我是你的索引。

P.S:你应该尽量不改变javascript中的内容,它确实会让你的代码容易受到攻击。 re[i]= this.state.reservation1[i]

也许你可以试试这段代码: -

const re = [];
const reservation1 = [
      {name:"8:30",active:true,dayindex:1},
      {name:"jad",active:true,dayindex:3},
      {name:"tony",active:true,dayindex:4},
      {name:"",active:false,dayindex:6},
    ];



  reservation1.map((datum,index)=> {
    if (datum) {
      re.push(datum)
    } else {
      re.push({
        name: "",
        active: false,
        dayIndex: 0
      });
    }
  })

  console.log(re[1].dayindex);