将数组值推入对象

时间:2020-07-11 05:59:25

标签: javascript object push

我正在练习使用对象,但在将值推入值数组时遇到问题。令人讨厌的行似乎是:

profile.myChildren.push(children[ch]); 

我得到了错误:

*Uncaught TypeError: Cannot read property 'push' of undefined ...*.

此外,实际上是否需要功能P​​rofile()?它似乎不会影响输出。任何帮助将不胜感激。

代码:

        let name = ['bob', 'carol', 'ted', 'alice'];
        let numChildren = [2, 1, 3, 2];
        let children = ['tom', 'fred', 'alec', 'fran', 'deb', 'kate', 'rob', 'pete'];
        let myChildren = [];
        let start = [];
        let finish = [];
        let profile;

        function createProfile(name, children, myChildren) {

            start[0] = 0;
            for (let i = 0; i < name.length; i++) { //for each parent(fname)
                profile = new Object();
                profile.firstName = name[i];
                profile.numChildren = numChildren[i];

                finish[i] = start[i] + numChildren[i] - 1;
                start[i + 1] = finish[i] + 1;

                for (let ch = start[i]; ch <= finish[i]; ch++) {
                    profile.myChildren.push(children[ch]);    
                }
                console.log(profile)
            }
        }

        function Profile(name, children, myChildren) {
            this.name = name;
            this.children = children;
            this.myChildren = myChildren;
        }

        createProfile(name, children, myChildren);

1 个答案:

答案 0 :(得分:-1)

在推送之前,您需要将profile.myChildren定义为数组。

function createProfile(name, children, myChildren) {

            start[0] = 0;
            for (let i = 0; i < name.length; i++) { //for each parent(fname)
                profile = new Object();
                profile.firstName = name[i];
                profile.numChildren = numChildren[i];
                finish[i] = start[i] + numChildren[i] - 1;
                start[i + 1] = finish[i] + 1;
                
                // Add the following line
                profile.myChildren = [];                

                for (let ch = start[i]; ch <= finish[i]; ch++) {
                    profile.myChildren.push(children[ch]);    
                }
                console.log(profile)
            }
        }