鍍金池/ 問答/HTML/ 前端報錯Cannot read property 'push' of undef

前端報錯Cannot read property 'push' of undefined

1.數(shù)據(jù)區(qū)聲明變量

        ruleForm: {
            role:'',
            sdemands:'',
            demands: []
        },

2.獲得服務(wù)器返回數(shù)據(jù)(服務(wù)器端返回role,sdemands,沒有demands數(shù)據(jù)),賦值this.ruleForm=...(這個沒有問題)
具體需求如下:
sdemands數(shù)據(jù)形式如下:a(1),b(2)
想要將sdemands解析并賦值給demands,是的demands變量形式如下:

demands:[
    {value1:a,value2:1},
    {value1:b,value2:2}
]

3.操作如下,但是前段報錯506 Uncaught TypeError: Cannot read property 'push' of undefined

                    var ded=this.ruleForm.sdemands.split(',');
                    var ded1='';
                    var ded2='';
                    for(var i=0;i<ded.length;i++){
                        ded1=ded[i].split('(')[0];
                        ded2=ded[i].split('(')[1];
                        ded2=ded2.substring(0,ded2.length-1);
                        this.ruleForm.demands.push({value1: ded1, value2: ded2, key: Date.now()});
                    }
                    
                    

補充一下:先聲明數(shù)組test,賦值給test,然后test在復(fù)制給demands就好了,但是有沒有更好的解決辦法

                    var test=[];
                    var ded=this.ruleForm.sdemands.split(',');
                    var ded1='';
                    var ded2='';
                    for(var i=0;i<ded.length;i++){
                        ded1=ded[i].split('(')[0];
                        ded2=ded[i].split('(')[1];
                        ded2=ded2.substring(0,ded2.length-1);
                        test.push({value1: ded1, value2: ded2, key: Date.now()});
                    }
                    console.log(test);
                    this.ruleForm.demands=test;
                    console.log(this.ruleForm.demands);
回答
編輯回答
鹿惑
2.獲得服務(wù)器返回數(shù)據(jù)(服務(wù)器端返回role,sdemands,沒有demands數(shù)據(jù)),賦值this.ruleForm=...(這個沒有問題)

估計你在第2步賦值操作的時候demands丟失了。
改成:
this.ruleForm.role=...;
this.ruleForm.sdemands=...;

2018年8月29日 08:29