pu sh значения массива в Object - PullRequest
0 голосов
/ 11 июля 2020

Я практикуюсь в использовании объектов, и у меня проблемы с помещением значений в массив значений. Непринятая строка выглядит так:

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

Я получаю сообщение об ошибке:

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

Кроме того, действительно ли нужна функция Profile ()? Похоже, это не влияет на результат. Приветствуется любая помощь.

Код:

        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 голосов
/ 11 июля 2020

Вам необходимо определить 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)
            }
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...