【问题标题】:How to push an array into the object in JavaScript?如何将数组推送到 JavaScript 中的对象中?
【发布时间】:2021-12-05 19:29:18
【问题描述】:

我创建了一个数组,我必须向用户询问新数据,然后我必须将此新信息添加到我的原始数组中,但是当我尝试添加由用户。

如何将新歌曲(歌曲名称和持续时间)添加到我的原始数组中?

这是我的代码:

    let discos = [];
    
    let disco1 = {
        discoName: 'Disco Name ',
        band: 'Catupecumachu',
        code: 1,
        songs: [
            {
                'songName': 'song1',
                'duration': 200,
            },
            {
                'songName': 'song2',
                'duration': 180,
            },
            {
                'songName': 'song3',
                'duration': 90,
            },
        ],
    };
    let disco2 = {
        discoName: 'Disco Name',
        band: 'U2',
        code: 2,
        songs: [
            {
                'songName': 'song1',
                'duration': 200,
            },
            {
                'songName': 'song2',
                'duration': 180,
            },
            {
                'songName': 'song3',
                'duration': 90,
            },
        ],
    };
    let discoUser = {
        discoName: '',
        band: '',
        code: '',
        songs: [
            {
                'songName': '',
                'duration': '',
            },
        ],
    };

discos.push(disco1, disco2, discoUser);

  do{        
     discoUser['discoName'] = prompt('discoName');
     discoUser['band'] = prompt('band');
     discoUser['code'] = prompt('code');
  }while(confirm('Continue?'));

【问题讨论】:

    标签: javascript arrays push prompt


    【解决方案1】:

    按照您的代码示例,您可以在最后一个提示行之后尝试此操作:

    const songName = prompt('song name');
    const duration = prompt('duration');
    discoUser.songs.push({songName,duration});
    

    更新 1:

    刚刚更新以在开发人员工具控制台上显示此测试:

    【讨论】:

    • 我试过了,还是不行:/
    • 那么请用您尝试过的内容更新您的代码,因为我很确定这可行:)
    • 对不起!我是super Junior 哈哈 可以了,非常感谢!!!
    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2021-11-13
    • 2021-10-28
    • 2020-05-21
    相关资源
    最近更新 更多