【问题标题】:push array values into Object将数组值推入 Object
【发布时间】:2023-03-08 21:26:01
【问题描述】:

我正在练习使用对象,但在将值推送到值数组时遇到问题。违规行似乎是:

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

【问题讨论】:

  • 您需要先定义 myChildren,就像一个空数组应该做的那样。 profile.myChildren = []

标签: javascript object push


【解决方案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)
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 2016-06-14
    • 2020-08-03
    • 2010-11-20
    • 2017-04-16
    • 2013-05-17
    • 1970-01-01
    • 2013-12-03
    相关资源
    最近更新 更多