简体   繁体   English

将数组值推送到 Object

[英]push array values into Object

I am practicing using Objects, and have problems pushing values into an array of values.The offending line appears to be:我正在练习使用对象,并且在将值推入值数组时遇到问题。违规行似乎是:

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

I get the error:我得到错误:

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

Also, is the function Profile() actually needed?另外,function Profile() 真的需要吗? It doesn't appear to affect the output.它似乎不会影响 output。 Any help would be appreciated.任何帮助,将不胜感激。

Code:代码:

        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);

You need to define profile.myChildren as an array before pushing.您需要在推送之前将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)
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM